Search Results

Search found 335 results on 14 pages for 'httpclient'.

Page 12/14 | < Previous Page | 8 9 10 11 12 13 14  | Next Page >

  • Twitter4J throws exception in TwitterFactory

    - by Philipp Andre
    Hello Guys, i'm trying to access twitter via oauth. Therefore, i registered my app, downloaded Twitter4j, added the jars in my Eclipse-Project, and then tried to execute the following code: Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance("[key]","[secretKey]); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println(requestToken.getAuthorizationURL()); But it raises the following exception: [Sat May 29 11:19:11 CEST 2010]Using class twitter4j.internal.logging.StdOutLoggerFactory as logging factory. [Sat May 29 11:19:11 CEST 2010]Use twitter4j.internal.http.alternative.HttpClientImpl as HttpClient implementation. Exception in thread "main" java.lang.AssertionError: java.lang.reflect.InvocationTargetException at twitter4j.internal.http.HttpClientFactory.getInstance(HttpClientFactory.java:71) at twitter4j.internal.http.HttpClientWrapper.<init>(HttpClientWrapper.java:59) at twitter4j.http.OAuthAuthorization.init(OAuthAuthorization.java:83) at twitter4j.http.OAuthAuthorization.<init>(OAuthAuthorization.java:74) at twitter4j.TwitterFactory.getOAuthAuthorizedInstance(TwitterFactory.java:112) at MainProgram.main(MainProgram.java:18) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at twitter4j.internal.http.HttpClientFactory.getInstance(HttpClientFactory.java:65) ... 5 more Caused by: java.lang.NoClassDefFoundError: org/apache/http/impl/client/DefaultHttpClient at twitter4j.internal.http.alternative.HttpClientImpl.<init>(HttpClientImpl.java:63) ... 10 more I currently can't figure out why ... can you please give me some suggestions? Best regards Philipp

    Read the article

  • Using Groovy as a scripting language...

    - by Zombies
    I prefer to use scripting languages for short tasks, anything such as a really simple http bot, bulk importing/exporting data to/from somewhere, etc etc... Basic throw-away scripts and simple stuff. The point being, that a scripting language is just an efficient tool to write quick programs with. As for my understanding of Groovy at this point... If you were to program in Groovy, and you wan't to write a quick script, wouldn't you be forced to going back to regular java syntax (and we know how that can be convoluted compared to a scripting language) in order to do anything more complicated? For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient? To me, the point of a scripting language is for quickly typed and less forced constructs. And here is another thing, it doesn't seem that there is any incentive for groovy based libraries to be developed when there are already so many good java one's out there, thus making groovy appear to be a Java dependent language with minor scripting features. So right now I am wondering if I could switch to Groovy as a scripting language or continue to use a more common scripting language such as Perl, Python or Ruby.

    Read the article

  • httprequest handle time delays till having response

    - by bourax webmaster
    I have an application that calls a function to send JSON object to a REST API, my problem is how can I handle time delays and repeat this function till i have a response from the server in case of interrupted network connexion ?? I try to use the Handler but i don't know how to stop it when i get a response !!! here's my function that is called when button clicked : protected void sendJson(final String name, final String email, final String homepage,final Long unixTime,final String bundleId) { Thread t = new Thread() { public void run() { Looper.prepare(); //For Preparing Message Pool for the child Thread HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit HttpResponse response; JSONObject json = new JSONObject(); //creating meta object JSONObject metaJson = new JSONObject(); try { HttpPost post = new HttpPost("http://util.trademob.com:5000/cards"); metaJson.put("time", unixTime); metaJson.put("bundleId", bundleId); json.put("name", name); json.put("email", email); json.put("homepage", homepage); //add the meta in the root object json.put("meta", metaJson); StringEntity se = new StringEntity( json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); String authorizationString = "Basic " + Base64.encodeToString( ("tester" + ":" + "tm-sdktest").getBytes(), Base64.NO_WRAP); //Base64.NO_WRAP flag post.setHeader("Authorization", authorizationString); response = client.execute(post); String temp = EntityUtils.toString(response.getEntity()); Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show(); } catch(Exception e) { e.printStackTrace(); } Looper.loop(); //Loop in the message queue } }; t.start(); }

    Read the article

  • MultipartFormDataContent Access to patch xx is denied

    - by Florian Schaal
    So I'm trying to upload a pdf file to a restapi. For some reason I the application cant get access to the files on my pc. The code im using to upload: public void Upload(string token, string FileName, string FileLocation, string Name, int TypeId, int AddressId, string CompanyName, string StreetNr, string Zip, string City, string CountryCode, string CustomFieldName, string CustomFieldValue) { var client = new HttpClient(); client.BaseAddress = _API.baseAddress; //upload a new form client.DefaultRequestHeaders.Date = DateTime.Now; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token); using (var multiPartContent = new MultipartFormDataContent()) { //get te bytes from a file byte[] pdfData; using (var pdf = new FileStream(@FileLocation, FileMode.Open))//Here i get the error. { pdfData = new byte[pdf.Length]; pdf.Read(pdfData, 0, (int)pdf.Length); } var fileContent = new ByteArrayContent(pdfData); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = FileName + ".pdf" }; //add the bytes to the multipart message multiPartContent.Add(fileContent); //make a json message var json = new FormRest { Name = Name, TypeId = TypeId, AddressId = AddressId, CompanyName = CompanyName, StreetNr = StreetNr, Zip = Zip, City = City, CountryCode = CountryCode, CustomFields = new List<CustomFieldRest> { new CustomFieldRest {Name = CustomFieldName, Value = CustomFieldValue} } }; var Content = new JsonContent(json); //add the json message to the multipart message multiPartContent.Add(Content); var result = client.PostAsync("forms", multiPartContent).Result; } } }

    Read the article

  • Apache tomcat7 + couchdb in the same host

    - by demotics2002
    I couldn't find any guide on the internet about how to make them work together. I found some couchdb tutorials but they are mostly having the web pages hosted in couchdb's own webserver. My requirement: 1. Use tomcat 7 (or other versions) - i will be using jsp for the website. It has some features that require file upload and processing of files, file generation, and etc., that will require java. It also has admin console that will require the next item, 2. ExtJS (maybe V4) - I will be needing this in the admin console page for restful access to couchdb and other ui components (sorry but I am not considering jquery at the moment because I am already familiar with . 3. Couchdb - because the client needs a dynamic structure of data. Now my question is how to make tomcat and couchdb run on the same host (and port of course)? As much as possible I would like to avoid making my pages doing cross domain js calls. Worst case I may have to create a servlet that overrides put|get|post|delete that calls couchdb (either by using a driver or httpclient).

    Read the article

  • android/rails multipart upload problem

    - by trioglobal
    My problem is that I try to upload an image and some text values to an rails server, and the text values end up as files, insted of just param values. How the post looks on the server Parameters: {"action"="create", "controller"="problems", "problem"={"lon"=#File:/tmp/RackMultipart20100404-598-8pi1vj-0, "photos_attributes"={"0"={"image"=#File:/tmp/RackMultipart20100404-598-pak6jk-0}}, "subject"=#File:/tmp/RackMultipart20100404-598-nje11p-0, "category_id"=#File:/tmp/RackMultipart20100404-598-ijy1oo-0, "lat"=#File:/tmp/RackMultipart20100404-598-1a7140w-0, "email"=#File:/tmp/RackMultipart20100404-598-1b7w6jp-0}} part of the android code try { File file = new File(Environment.getExternalStorageDirectory(), "FMS_photo.jpg"); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://homepage.com/path"); FileBody bin = new FileBody(file); Charset chars = Charset.forName("UTF-8"); MultipartEntity reqEntity = new MultipartEntity(); //reqEntity.addPart("problem[subject]", subject); reqEntity.addPart("problem[photos_attributes][0][image]", bin); reqEntity.addPart("problem[category_id]", new StringBody("17", chars)); //.... post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } return true; } catch (Exception ex) { //Log.v(LOG_TAG, "Exception", ex); globalStatus = UPLOAD_ERROR; serverResponse = ""; return false; } finally { }

    Read the article

  • Android: Unable to make httprequest behind firewall

    - by Yang
    The standard getUrlContent works welll when there is no firewall. But I got exceptions when I try to do it behind a firewall. I've tried to set "http proxy server" in AVD manager, but it didn't work. Any idea how to correctly set it up? protected static synchronized String getUrlContent(String url) throws ApiException { if(url.equals("try")){ return "thanks"; } if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }

    Read the article

  • How to determine which source files are required for an Eclipse run configuration

    - by isme
    When writing code in an Eclipse project, I'm usually quite messy and undisciplined in how I create and organize my classes, at least in the early hacky and experimental stages. In particular, I create more than one class with a main method for testing different ideas that share most of the same classes. If I come up with something like a useful app, I can export it to a runnable jar so I can share it with friends. But this simply packs up the whole project, which can become several megabytes big if I'm relying on large library such as httpclient. Also, if I decide to refactor my lump of code into several projects once I work out what works, and I can't remember which source files are used in a particular run configuration, all I can do it copy the main class to a new project and then keep copying missing types till the new project compiles. Is there a way in Eclipse to determine which classes are actually used in a particular run configuration? EDIT: Here's an example. Say I'm experimenting with web scraping, and so far I've tried to scrape the search-result pages of both youtube.com and wrzuta.pl. I have a bunch of classes that implement scraping in general, a few that are specific to each of youtube and wrzuta. On top of this I have a basic gui common to both scrapers, but a few wrzuta- and youtube-specific buttons and options. The WrzutaGuiMain and YoutubeGuiMain classes each contain a main method to configure and show the gui for each respective website. Can Eclipse look at each of these to determine which types are referenced?

    Read the article

  • How to get the Video-ID of a just uploaded Youtube movie

    - by murze
    Hi, how can i get the video-id of a just uploaded Youtube movie? I'm using this code: $yt = new Zend_Gdata_YouTube($httpClient); // create a new Zend_Gdata_YouTube_VideoEntry object $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry(); // create a new Zend_Gdata_App_MediaFileSource object $filesource = $yt->newMediaFileSource('mytestmovie.mov'); $filesource->setContentType('video/quicktime'); // set slug header $filesource->setSlug('mytestmovie.mov'); // add the filesource to the video entry $myVideoEntry->setMediaSource($filesource); $myVideoEntry->setVideoTitle('My Test Movie'); $myVideoEntry->setVideoDescription('My Test Movie'); $myVideoEntry->setVideoCategory('Comedy'); // Note that category must be a valid YouTube category ! // set keywords, please note that this must be a comma separated string // and that each keyword cannot contain whitespace $myVideoEntry->setVideoTags('cars, funny'); // upload URI for the currently authenticated user $uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads'; // try to upload the video, catching a Zend_Gdata_App_HttpException if available // or just a regular Zend_Gdata_App_Exception try { $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry'); } catch (Zend_Gdata_App_HttpException $httpException) { echo $httpException->getRawResponseBody(); } catch (Zend_Gdata_App_Exception $e) { echo $e->getMessage(); } I assume it 'll be a property of $newEntry but i can't seem to find it! Thanks!

    Read the article

  • Authentication using cookie key with asynchronous callback

    - by greg
    I need to write authentication function with asynchronous callback from remote Auth API. Simple authentication with login is working well, but authorization with cookie key, does not work. It should checks if in cookies present key "lp_login", fetch API url like async and execute on_response function. The code almost works, but I see two problems. First, in on_response function I need to setup secure cookie for authorized user on every page. In code user_id returns correct ID, but line: self.set_secure_cookie("user", user_id) does't work. Why it can be? And second problem. During async fetch API url, user's page has loaded before on_response setup cookie with key "user" and the page will has an unauthorized section with link to login or sign on. It will be confusing for users. To solve it, I can stop loading page for user who trying to load first page of site. Is it possible to do and how? Maybe the problem has more correct way to solve it? class BaseHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get_current_user(self): user_id = self.get_secure_cookie("user") user_cookie = self.get_cookie("lp_login") if user_id: self.set_secure_cookie("user", user_id) return Author.objects.get(id=int(user_id)) elif user_cookie: url = urlparse("http://%s" % self.request.host) domain = url.netloc.split(":")[0] try: username, hashed_password = urllib.unquote(user_cookie).rsplit(',',1) except ValueError: # check against malicious clients return None else: url = "http://%s%s%s/%s/" % (domain, "/api/user/username/", username, hashed_password) http = tornado.httpclient.AsyncHTTPClient() http.fetch(url, callback=self.async_callback(self.on_response)) else: return None def on_response(self, response): answer = tornado.escape.json_decode(response.body) username = answer['username'] if answer["has_valid_credentials"]: author = Author.objects.get(email=answer["email"]) user_id = str(author.id) print user_id # It returns needed id self.set_secure_cookie("user", user_id) # but session can's setup

    Read the article

  • org.apache.http.conn.HttpHostConnectException:Connection to http://172.20.38.143 refused

    - by Passion
    I have developed client server Application .I am accessing mysql with php running on my machine and client running on my cell which is connected to machine.WI-FI is also switched ON. Internet Permission are also added in Manifest file but then also the i encounter error 172.20.38.143 is IP OF MY MACHINE 06-01 13:20:10.391: W/System.err(11157): org.apache.http.conn.HttpHostConnectException: Connection to http://172.20.38.143 refused 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:674) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511) 06-01 13:20:10.401: W/System.err(11157): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.library.JSONParser.getJSONFromUrl(JSONParser.java:42) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.library.UserFunctions.registerUser(UserFunctions.java:59) 06-01 13:20:10.401: W/System.err(11157): at nineandroid.net.example.RegisterActivity$1.onClick(RegisterActivity.java:52) 06-01 13:20:10.411: W/System.err(11157): at android.view.View.performClick(View.java:3567) 06-01 13:20:10.411: W/System.err(11157): at android.view.View$PerformClick.run(View.java:14224) 06-01 13:20:10.411: W/System.err(11157): at android.os.Handler.handleCallback(Handler.java:605) 06-01 13:20:10.411: W/System.err(11157): at android.os.Handler.dispatchMessage(Handler.java:92) 06-01 13:20:10.411: W/System.err(11157): at android.os.Looper.loop(Looper.java:137) 06-01 13:20:10.411: W/System.err(11157): at android.app.ActivityThread.main(ActivityThread.java:4517) 06-01 13:20:10.411: W/System.err(11157): at java.lang.reflect.Method.invokeNative(Native Method) 06-01 13:20:10.411: W/System.err(11157): at java.lang.reflect.Method.invoke(Method.java:511) 06-01 13:20:10.411: W/System.err(11157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 06-01 13:20:10.421: W/System.err(11157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 06-01 13:20:10.421: W/System.err(11157): at dalvik.system.NativeStart.main(Native Method) 06-01 13:20:10.421: W/System.err(11157): Caused by: java.net.ConnectException: failed to connect to /172.20.38.143 (port 80): connect failed: ENETUNREACH (Network is unreachable) 06-01 13:20:10.431: W/System.err(11157): at libcore.io.IoBridge.connect(IoBridge.java:114) 06-01 13:20:10.431: W/System.err(11157): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 06-01 13:20:10.431: W/System.err(11157): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 06-01 13:20:10.431: W/System.err(11157): at java.net.Socket.connect(Socket.java:848) 06-01 13:20:10.431: W/System.err(11157): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 06-01 13:20:10.431: W/System.err(11157): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 06-01 13:20:10.431: W/System.err(11157): ... 20 more 06-01 13:20:10.431: W/System.err(11157): Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.Posix.connect(Native Method) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 06-01 13:20:10.441: W/System.err(11157): at libcore.io.IoBridge.connect(IoBridge.java:112) 06-01 13:20:10.441: W/System.err(11157): ... 25 more 06-01 13:20:10.441: E/Buffer Error(11157): Error converting result java.lang.NullPointerException 06-01 13:20:10.451: E/JSON Parser(11157): Error parsing data org.json.JSONException: End of input at character 0 of 06-01 13:20:10.451: D/AndroidRuntime(11157): Shutting down VM 06-01 13:20:10.451: W/dalvikvm(11157): threadid=1: thread exiting with uncaught exception (group=0x40c0aa68) 06-01 13:20:10.451: E/AndroidRuntime(11157): FATAL EXCEPTION: main 06-01 13:20:10.451: E/AndroidRuntime(11157): java.lang.NullPointerException 06-01 13:20:10.451: E/AndroidRuntime(11157): at nineandroid.net.example.RegisterActivity$1.onClick(RegisterActivity.java:56) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.view.View.performClick(View.java:3567) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.view.View$PerformClick.run(View.java:14224) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Handler.handleCallback(Handler.java:605) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Handler.dispatchMessage(Handler.java:92) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.os.Looper.loop(Looper.java:137) 06-01 13:20:10.451: E/AndroidRuntime(11157): at android.app.ActivityThread.main(ActivityThread.java:4517) 06-01 13:20:10.451: E/AndroidRuntime(11157): at java.lang.reflect.Method.invokeNative(Native Method) 06-01 13:20:10.451: E/AndroidRuntime(11157): at java.lang.reflect.Method.invoke(Method.java:511) 06-01 13:20:10.451: E/AndroidRuntime(11157): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 06-01 13:20:10.451: E/AndroidRuntime(11157): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 06-01 13:20:10.451: E/AndroidRuntime(11157): at dalvik.system.NativeStart.main(Native Method) UserFunctions.java to call jsonParser public class UserFunctions { private JSONParser jsonParser; private static String loginURL = "http://172.20.38.143/ah_login_api/"; private static String registerURL = "http://172.20.38.143/ah_login_api/"; private static String login_tag = "login"; private static String register_tag = "register"; // constructor public UserFunctions(){ jsonParser = new JSONParser(); } /** * function make Login Request * @param email * @param password * */ public JSONObject loginUser(String email, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", login_tag)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); JSONObject json = jsonParser.getJSONFromUrl(loginURL, params); // return json // Log.e("JSON", json.toString()); return json; } /** * function make Login Request * @param name * @param email * @param password * */ public JSONObject registerUser(String name, String email, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", register_tag)); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); // getting JSON Object JSONObject json = jsonParser.getJSONFromUrl(registerURL, params); // return json return json; } /** * Function get Login status * */ public boolean isUserLoggedIn(Context context){ DatabaseHandler db = new DatabaseHandler(context); int count = db.getRowCount(); if(count > 0){ // user logged in return true; } return false; } /** * Function to logout user * Reset Database * */ public boolean logoutUser(Context context){ DatabaseHandler db = new DatabaseHandler(context); db.resetTables(); return true; } } jsonParser.java public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); Log.e("JSON", json); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } RegisterActivity.java public class RegisterActivity extends Activity { Button btnRegister; Button btnLinkToLogin; EditText inputFullName; EditText inputEmail; EditText inputPassword; TextView registerErrorMsg; // JSON Response node names private static String KEY_SUCCESS = "success"; private static String KEY_UID = "uid"; private static String KEY_NAME = "name"; private static String KEY_EMAIL = "email"; private static String KEY_CREATED_AT = "created_at"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); // Importing all assets like buttons, text fields inputFullName = (EditText) findViewById(R.id.registerName); inputEmail = (EditText) findViewById(R.id.registerEmail); inputPassword = (EditText) findViewById(R.id.registerPassword); btnRegister = (Button) findViewById(R.id.btnRegister); btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); registerErrorMsg = (TextView) findViewById(R.id.register_error); // Register Button Click event btnRegister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputFullName.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); UserFunctions userFunction = new UserFunctions(); JSONObject json = userFunction.registerUser(name, email, password); // check for login response try { if (json.getString(KEY_SUCCESS) != null) { registerErrorMsg.setText(""); String res = json.getString(KEY_SUCCESS); if(Integer.parseInt(res) == 1){ // user successfully registred // Store user details in SQLite Database DatabaseHandler db = new DatabaseHandler(getApplicationContext()); JSONObject json_user = json.getJSONObject("user"); // Clear all previous data in database userFunction.logoutUser(getApplicationContext()); db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT)); // Launch Dashboard Screen Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class); // Close all views before launching Dashboard dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(dashboard); // Close Registration Screen finish(); }else{ // Error in registration registerErrorMsg.setText("Error occured in registration"); } } } catch (JSONException e) { e.printStackTrace(); } } }); // Link to Login Screen btnLinkToLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); // Close Registration View finish(); } }); } }

    Read the article

  • JAVA - Download PDF file from Webserver

    - by Augusto Picciani
    I need to download a pdf file from a webserver to my pc and save it locally. I used Httpclient to connect to webserver and get the content body: HttpEntity entity=response.getEntity(); InputStream in=entity.getContent(); String stream = CharStreams.toString(new InputStreamReader(in)); int size=stream.length(); System.out.println("stringa html page LENGTH:"+stream.length()); System.out.println(stream); SaveToFile(stream); Then i save content in a file: //check CRLF (i don't know if i need to to this) String[] fix=stream.split("\r\n"); File file=new File("C:\\Users\\augusto\\Desktop\\progetti web\\test\\test2.pdf"); PrintWriter out = new PrintWriter(new FileWriter(file)); for (int i = 0; i < fix.length; i++) { out.print(fix[i]); out.print("\n"); } out.close(); I also tried to save a String content to file directly: OutputStream out=new FileOutputStream("pathPdfFile"); out.write(stream.getBytes()); out.close(); But the result is always the same: I can open pdf file but i can see white pages only. Does the mistake is around pdf stream and endstream charset encoding? Does pdf content between stream and endStream need to be manipulate in some others way?

    Read the article

  • Efficiently sending protocol buffer messages with http on an android platform

    - by Ben Griffiths
    I'm trying to send messages generated by Google Protocol Buffer code via a simple HTTP scheme to a server. What I have currently have implemented is here (forgive the obvious incompletion...): HttpClient client = new DefaultHttpClient(); String url = "http://192.168.1.69:8888/sdroidmarshal"; HttpPost postRequest = new HttpPost(url); String proto = offers.build().toString(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("sdroidmsg", proto)); postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(postRequest, responseHandler); } catch (Throwable t) { } I'm not that experienced with communications over the internet and no more so with HTTP - while I do understand the basics... So my question, before I blindly develop the rest of the application around this, is whether or not this is particularly efficient? I ideally would like to keep messages small and I assume toString() adds some unnecessary formatting.

    Read the article

  • Why thread in background is not waiting for task to complete?

    - by Haris Hasan
    I am playing with async await feature of C#. Things work as expected when I use it with UI thread. But when I use it in a non-UI thread it doesn't work as expected. Consider the code below private void Click_Button(object sender, RoutedEventArgs e) { var bg = new BackgroundWorker(); bg.DoWork += BgDoWork; bg.RunWorkerCompleted += BgOnRunWorkerCompleted; bg.RunWorkerAsync(); } private void BgOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { } private async void BgDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { await Method(); } private static async Task Method() { for (int i = int.MinValue; i < int.MaxValue; i++) { var http = new HttpClient(); var tsk = await http.GetAsync("http://www.ebay.com"); } } When I execute this code, background thread don't wait for long running task in Method to complete. Instead it instantly executes the BgOnRunWorkerCompleted after calling Method. Why is that so? What am I missing here? P.S: I am not interested in alternate ways or correct ways of doing this. I want to know what is actually happening behind the scene in this case? Why is it not waiting?

    Read the article

  • What is the right pattern for a async data fetching method in .net async/await

    - by s093294
    Given a class with a method GetData. A few other clients call GetData, and instead of it fetching data each time, i would like to create a pattern where the first call starts the task to get the data, and the rest of the calls wait for the task to complete. private Task<string> _data; private async Task<string> _getdata() { return "my random data from the net"; //get_data_from_net() } public string GetData() { if(_data==null) _data=_getdata(); _data.wait(); //are there not a problem here. cant wait a task that is already completed ? if(_data.status != rantocompletion) _data.wait() is not any better, it might complete between the check and the _data.wait? return _data.Result; } How would i do the pattern correctly? (Solution) private static object _servertime_lock = new object(); private static Task<string> _servertime; private static async Task<string> servertime() { try { var thetvdb = new HttpClient(); thetvdb.Timeout = TimeSpan.FromSeconds(5); // var st = await thetvdb.GetStreamAsync("http://www.thetvdb.com/api/Updates.php?type=none"); var response = await thetvdb.GetAsync("http://www.thetvdb.com/api/Updates.php?type=none"); response.EnsureSuccessStatusCode(); Stream stream = await response.Content.ReadAsStreamAsync(); XDocument xdoc = XDocument.Load(stream); return xdoc.Descendants("Time").First().Value; } catch { return null; } } public static async Task<string> GetServerTime() { lock (_servertime_lock) { if (_servertime == null) _servertime = servertime(); } var time = await _servertime; if (time == null) _servertime = null; return time; }

    Read the article

  • Display HttpResponse (string from Handler) in new WebView

    - by datguywhowanders
    I have the following code in a form's submit button onClickListener: String action, user, pwd, user_field, pwd_field; action = "theURL"; user_field = "id"; pwd_field = "pw"; user = "username"; pwd = "password!!"; List<NameValuePair> myList = new ArrayList<NameValuePair>(); myList.add(new BasicNameValuePair(user_field, user)); myList.add(new BasicNameValuePair(pwd_field, pwd)); HttpParams params = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(action); HttpResponse end = null; String endResult = null; try { post.setEntity(new UrlEncodedFormEntity(myList)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { HttpResponse response = client.execute(post); end = response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasicResponseHandler myHandler = new BasicResponseHandler(); try { endResult = myHandler.handleResponse(end); } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } How can I take the resulting string (endResult) and start a new activity using an intent that will open webview and load the html?

    Read the article

  • Android: Problems downloading images and converting to bitmaps

    - by Mike
    Hi all, I am working on an application that downloads images from a url. The problem is that only some images are being correctly downloaded and others are not. First off, here is the problem code: public Bitmap downloadImage(String url) { HttpClient client = new DefaultHttpClient(); HttpResponse response = null; try { response = client.execute(new HttpGet(url)); } catch (ClientProtocolException cpe) { Log.i(LOG_FILE, "client protocol exception"); return null; } catch (IOException ioe) { Log.i(LOG_FILE, "IOE downloading image"); return null; } catch (Exception e) { Log.i(LOG_FILE, "Other exception downloading image"); return null; } // Convert images from stream to bitmap object try { Bitmap image = BitmapFactory.decodeStream(response.getEntity().getContent()); if(image==null) Log.i(LOG_FILE, "image conversion failed"); return image; } catch (Exception e) { Log.i(LOG_FILE, "Other exception while converting image"); return null; } } So what I have is a method that takes the url as a string argument and then downloads the image, converts the HttpResponse stream to a bitmap by means of the BitmapFactory.decodeStream method, and returns it. The problem is that when I am on a slow network connection (almost always 3G rather than Wi-Fi) some images are converted to null--not all of them, only some of them. Using a Wi-Fi connection works perfectly; all the images are downloaded and converted properly. Does anyone know why this is happening? Or better, how can I fix this? How would I even go about testing to determine the problem? Any help is awesome; thank you!

    Read the article

  • Address family not supported by protocol exception

    - by srg
    I'm trying to send a couple of values from an android application to a web service which I've setup. I'm using Http Post to send them but when I run the application I get the error- request time failed java.net.SocketException: Address family not supported by protocol. I get this while debugging with both the emulator as well as a device connected by wifi. I've already added the internet permission using: <uses-permission android:name="android.permission.INTERNET" /> This is the code i'm using to send the values void insertData(String name, String number) throws Exception { String url = "http://192.168.0.12:8000/testapp/default/call/run/insertdbdata/"; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); try { List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("a", name)); params.add(new BasicNameValuePair("b", number)); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(post); }catch(Exception e){ e.printStackTrace(); } Also I know that my web service work fine because when I send the values from an html page it works fine - <form name="form1" action="http://192.168.0.12:8000/testapp/default/call/run/insertdbdata/" method="post"> <input type="text" name="a"/> <input type="text" name="b"/> <input type="submit"/> I've seen questions of similar problems but haven't really found a solution. Thanks

    Read the article

  • How to design authentication in a thick client, to be fail safe?

    - by Jay
    Here's a use case: I have a desktop application (built using Eclipse RCP) which on start, pops open a dialog box with 'UserName' and 'Password' fields in it. Once the end user, inputs his UserName and Password, a server is contacted (a spring remote-servlet, with the client side being a spring httpclient: similar to the approaches here.), and authentication is performed on the server side. A few questions related to the above mentioned scenario: If said this authentication service were to go down, what would be the best way to handle further proceedings? Authentication is something that I cannot do away with. Would running the desktop client in a "limited" mode be a good idea? For instance, important features/menus/views will be disabled, rest of the application will be accessible? Should I have a back up authentication service running on a different machine, working as a backup? What are the general best-practices in this scenario? I remember reading about google gears and how it would let you edit and do stuff offline - should something like this be designed? Please let me know your design/architectural comments/suggestions. Appreciate your help.

    Read the article

  • Get 1 array from 2 arrays (using RestKit 0.20)

    - by Reez
    I'm using RestKit and was wondering how to combine two array's into one array. I already have the data being pulled in separately from API1 and API2, but I don't know how to combine them into 1 tableView. Each API is pulling in media, and I want the combined tableView to show the most recent media (like any standard timeline does these days). I will post any extra code or help as necessary, thanks so much! Below shows API1 + API2 being pulled in correctly, but not combined into the tableView. Only data from API1 shows in the tableView. ViewController.m @interface StackOverflowViewController () @property (strong, nonatomic) NSArray *hArray; @property (strong, nonatomic) NSArray *springs; @property (strong, nonatomic) RKObjectManager *eObjectManager; @property (strong, nonatomic) NSArray *iArray; @property (strong, nonatomic) NSArray *imagesArray; @property (strong, nonatomic) RKObjectManager *iObjectManager; // Wain @property (strong, nonatomic) NSMutableArray *tableDataList; // Laarme @property (nonatomic, strong) NSMutableArray *contentArray; @property (nonatomic, strong) NSDateFormatter *dateFormatter1; // Dan @property (nonatomic, strong) NSMutableArray *combinedModel; @end @implementation StackOverflowViewController @synthesize tableView = _tableView; @synthesize spring; @synthesize leaf; @synthesize theme; @synthesize hArray; @synthesize springs; @synthesize eObjectManager; @synthesize iArray; @synthesize imagesArray; @synthesize iObjectManager; // Wain @synthesize tableDataList; // Laarme @synthesize contentArray; @synthesize dateFormatter1; // Dan @synthesize combinedModel; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self configureRestKit]; [self loadMediaDan]; [self sortCombinedModel]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)configureRestKit { // API1 // initialize AFNetworking HTTPClient NSURL *baseURLE = [NSURL URLWithString:@"https://api.e.com"]; AFHTTPClient *clientE = [[AFHTTPClient alloc] initWithBaseURL:baseURLE]; // initialize RestKit RKObjectManager *eManager = [[RKObjectManager alloc] initWithHTTPClient:clientE]; self.eObjectManager = eManager; // setup object mappings RKObjectMapping *feedMapping = [RKObjectMapping mappingForClass:[Feed class]]; [feedMapping addAttributeMappingsFromArray:@[@"headline", @"premium", @"published", @"description"]]; RKObjectMapping *linksMapping = [RKObjectMapping mappingForClass:[Links class]]; RKObjectMapping *webMapping = [RKObjectMapping mappingForClass:[Web class]]; [webMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *mobileMapping = [RKObjectMapping mappingForClass:[Mobile class]]; [mobileMapping addAttributeMappingsFromArray:@[@"href"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[Images class]]; [imagesMapping addAttributeMappingsFromArray:@[@"height", @"width", @"url"]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"links" toKeyPath:@"links" withMapping:linksMapping]]; [feedMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"web" toKeyPath:@"web" withMapping:webMapping]]; [linksMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"mobile" toKeyPath:@"mobile" withMapping:mobileMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:feedMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"feed" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.eObjectManager addResponseDescriptor:responseDescriptor]; // API2 // initialize AFNetworking HTTPClient NSURL *baseURLI = [NSURL URLWithString:@"https://api.i.com"]; AFHTTPClient *clientI = [[AFHTTPClient alloc] initWithBaseURL:baseURLI]; // initialize RestKit RKObjectManager *iManager = [[RKObjectManager alloc] initWithHTTPClient:clientI]; self.iObjectManager = iManager; // setup object mappings RKObjectMapping *dataMapping = [RKObjectMapping mappingForClass:[Data class]]; [dataMapping addAttributeMappingsFromArray:@[@"link", @"created_time"]]; RKObjectMapping *imagesMapping = [RKObjectMapping mappingForClass:[ImagesI class]]; [IMapping addAttributeMappingsFromArray:@[@""]]; RKObjectMapping *standardResolutionMapping = [RKObjectMapping mappingForClass:[StandardResolution class]]; [standardResolutionMapping addAttributeMappingsFromArray:@[@"url", @"width", @"height"]]; RKObjectMapping *captionMapping = [RKObjectMapping mappingForClass:[Caption class]]; [captionMapping addAttributeMappingsFromArray:@[@"text", @"created_time"]]; RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]]; [userMapping addAttributeMappingsFromArray:@[@"username"]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"images" toKeyPath:@"images" withMapping:imagesMapping]]; [imagesMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"standard_resolution" toKeyPath:@"standard_resolution" withMapping:standardResolutionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"caption" toKeyPath:@"caption" withMapping:captionMapping]]; [dataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user" toKeyPath:@"user" withMapping:userMapping]]; // register mappings with the provider using a response descriptor RKResponseDescriptor *responseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping method:RKRequestMethodGET pathPattern:nil keyPath:@"data" statusCodes:[NSIndexSet indexSetWithIndex:200]]; [self.iObjectManager addResponseDescriptor:responseDescriptor2]; } - (void)loadMedia { // Laarme contentArray = [[NSMutableArray alloc] init]; [self sortByDates]; // API1 NSString *apikey = @kCLIENTKEY; NSDictionary *queryParams = @{@"apikey" : apikey,}; [self.eObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/n/?limit=4&leafs=%@&themes=%@", leafAbbreviation, themeID] // Changed limit to 4 for the time being parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { hArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No?: %@", error); }]; // API2 [self.iObjectManager getObjectsAtPath:[NSString stringWithFormat:@"v1/u/2/m/recent/?client_id=e999"] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { iArray = mappingResult.array; [self.tableView reloadData]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"No: %@", error); }]; } // Laarme - (void)sortByDates { NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init]; //Do the dateFormatter settings, you may have to use 2 NSDateFormatters if the format is different for Data & Feed //The initialization of the dateFormatter is done before the block, because its alloc/init take some time, and you may have to declare it with "__block" //Since in your edit you do that and it seems it's the same format, just do @property (nonatomic, strong) NSDateFormatter dateFormatter; NSArray *sortedArray = [contentArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { // Added Curly Braces around if else statements and used feedObject NSDate *aDate, *bDate; Feed *feedObject = (Feed *)a; Data *dataObject = (Data *)b; if ([a isKindOfClass:[Feed class]]) { //Feed *feedObject = (Feed *)a; aDate = [dateFormatter1 dateFromString:feedObject.published];} else { //if ([a isKindOfClass:[Data class]]) aDate = [dateFormatter2 dateFromString:dataObject.created_time];} if ([b isKindOfClass:[Feed class]]) { bDate = [dateFormatter1 dateFromString:feedObject.published];} else {//if ([b isKindOfClass:[Data class]]) bDate = [dateFormatter2 dateFromString:dataObject.created_time];} return [aDate compare:bDate]; }]; } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // API1 //return hArray.count; // API2 //return iArray.count; // API1 + API2 return hArray.count + iArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; if(indexPath.row < hArray.count) { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 1 TableViewCell *api1Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI1Cell"]; // Do everything you need to do with the api1Cell // Use the index in 'indexPath.row' to get the object from you array // API1 Feed *feedLocal = [hArray objectAtIndex:indexPath.row]; // API1 NSString *dateString = [self timeSincePublished:feedLocal.published]; NSString *headlineText = [NSString stringWithFormat:@"%@", feedLocal.headline]; NSString *descriptionText = [NSString stringWithFormat:@"%@", feedLocal.description]; NSString *premiumText = [NSString stringWithFormat:@"%@", feedLocal.premium]; api1Cell.labelHeadline.text = [NSString stringWithFormat:@"%@", headlineText]; api1Cell.labelPublished.text = dateString; api1Cell.labelDescription.text = descriptionText; // SDWebImage API1 if ([feedLocal.images count] == 0) { // Not sure anything needed here } else { Images *imageLocal = [feedLocal.images objectAtIndex:0]; NSString *imageURL = [NSString stringWithFormat:@"%@", imageLocal.url]; NSString *imageWith = [NSString stringWithFormat:@"%@", imageLocal.width]; NSString *imageHeight = [NSString stringWithFormat:@"%@", imageLocal.height]; __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api1Cell; } else { // Date Change NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM d, yyyy h:mma"]; // API 2 MRWebListTableViewCellTwo *api2Cell = [tableView dequeueReusableCellWithIdentifier:@"YourAPI2Cell"]; // Do everything you need to do with the api2Cell // Remember to use 'indexPath.row - hArray.count' as the index for getting an object for your second array // API 2 Data *dataLocal = [iArray objectAtIndex:indexPath.row - hArray.count]; // API 2 NSString *dateStringI = [self timeSincePublished:dataLocal.created_time]; NSString *captionTextI = [NSString stringWithFormat:@"%@", dataLocal.caption.text]; NSString *usernameI = [NSString stringWithFormat:@"%@", dataLocal.user.username]; api2Cell.labelHeadline.text = usernameI; api2Cell.labelDescription.text = captionTextI; api2Cell.labelPublished.text = dateStringI; // SDWebImage API 2 if ([dataLocal.images count] == 0) { NSLog(@"Images Count: %lu", (unsigned long)dataLocal.images.count); // Not sure anything needed here } else { ImagesI *imageLocalI = [dataLocal.images objectAtIndex:0]; StandardResolutionI *standardResolutionLocal = [imageLocalI.standard_resolution objectAtIndex:0]; NSString *imageURLI = [NSString stringWithFormat:@"%@", standardResolutionLocal.url]; NSString *imageWithI = [NSString stringWithFormat:@"%@", standardResolutionLocal.width]; NSString *imageHeightI = [NSString stringWithFormat:@"%@", standardResolutionLocal.height]; // 11.2 __weak UITableViewCell *wcell = cell; [cell.imageView setImageWithURL:[NSURL URLWithString:imageURLI] placeholderImage:[UIImage imageNamed:@"X"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // Something }]; } cell = api2Cell; } return cell; } Feed.h @property (nonatomic, strong) Links *links; @property (nonatomic, strong) NSString *headline; @property (nonatomic, strong) NSString *source; @property (nonatomic, strong) NSDate *published; @property (nonatomic, strong) NSString *description; @property (nonatomic, strong) NSString *premium; @property (nonatomic, strong) NSArray *images; Data.h @property (nonatomic, strong) NSString *link; @property (nonatomic, strong) NSDate *created_time; @property (nonatomic, strong) UserI *user; @property (nonatomic, strong) NSArray *images; @property (nonatomic, strong) CaptionI *caption;

    Read the article

  • Consume a JSON webservice and process data in Android

    - by user1783391
    I am trying to consume a the webservice below http://62.253.195.179/disaster/webservices/login.php?message=[{"email":"[email protected]","password":"welcome"}] This returns a JSON array [{"companyuserId":"2","name":"ben stein","superiorname":"Leon","departmentId":"26","departmentname":"Development","companyId":"23","UDID":"12345","isActive":"1","devicetoken":"12345","email":"[email protected]","phone":"5456465465654","userrole":"1","chngpwdStatus":"1"}] My code is below try{ String weblink = URLEncoder.encode("http://62.253.195.179/disaster/webservices/login.php?message=[{\"email\":\"[email protected]\",\"password\":\"welcome\"}]"); HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 7500; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 7500; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(); URI link = new URI(weblink); request.setURI(link); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); result = rd.readLine(); JSONObject myData = new JSONObject(result); JSONArray jArray = myData.getJSONArray(""); JSONObject steps = jArray.getJSONObject(0); String name = steps.getString("name"); } catch (JSONException e) { e.printStackTrace(); } But its not working and I am not 100% sure this is the best way to do it. 11-10 10:49:55.489: E/AndroidRuntime(392): java.lang.IllegalStateException: Target host must not be null, or set in parameters.

    Read the article

  • Android: Having trouble getting html from webpage

    - by Kyle
    Hi, I'm writing an android application that is supposed to get the html from a php page and use the parsed data from thepage. I've searched for this issue on here, and ended up using some code from an example another poster put up. Here is my code so far: HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { Log.d("first","first"); HttpResponse response = client.execute(request); String html = ""; Log.d("second","second"); InputStream in = response.getEntity().getContent(); Log.d("third","third"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Log.d("fourth","fourth"); StringBuilder str = new StringBuilder(); String line = null; Log.d("fifth","fifth"); while((line = reader.readLine()) != null) { Log.d("request line",line); } in.close(); } catch (ClientProtocolException e) { } catch (IOException e) { // TODO Auto-generated catch block Log.d("error", "error"); } Log.d("end","end"); } Like I said before, the url is a php page. Whenever I run this code, it prints out the first first message, but then prints out the error error message and then finally the end end message. I've tried modifying the headers, but I've had no luck with it. Any help would be greatly appreciated as I don't know what I'm doing wrong. Thanks!

    Read the article

  • Ruby - Nokogiri - Need to put node.value to an array

    - by r3nrut
    What I'm trying to do is read the value for all the nodes in this XML and put them into an array. This should be simple but for some reason it's driving me nuts. XML <ArrayOfAddress> <Address> <AddressId>297424fe-cfff-4ee1-8faa-162971d2645f</AddressId> <FirstName>George</FirstName> <LastName>Washington</LastName> <Address1>123 Main St</Address1> <Address2>Apt #611</Address2> <City>New York</City> <State>NY</State> <PostalCode>10110</PostalCode> <CountryCode>US</CountryCode> <EmailAddress>[email protected]</EmailAddress> <PhoneNumber>5555551234</PhoneNumber> <AddressType>CustomerAddress</AddressType> </Address> </ArrayOfAddress> Code class MassageRepsone def parse_resp @@get_address.url_builder #URL passed through HTTPClient - @@resp is the xml above doc = Nokogiri::XML::Reader(@@resp) @@values = doc.each do |node| node.value end end @@get_address.parse_resp obj = [@@values] Array(obj) p obj end The code snippet from above returns the following: 297424fe-cfff-4ee1-8faa-162971d2645f George Washington 123 Main St Apt #622 New York NY 10110 US test.test.com 5555551234 CustomerAddress I tried putting @@values to a string and applying chomp but that just prints the newlines as nil and puts quotes around the values. Not sure what the next step is or if I need to approach this differently with Nokogiri.

    Read the article

  • Write to PDF using PHP from android device

    - by Brent Mitchell
    I am trying to write to a pdf file on php server. I have sent variables to the server, create the pdf document, then have my phone download the document to view on device. The variables seem not to write on the php file. I have my code below public void postData() { try { Calculate calc = new Calculate(); HttpClient mClient = new DefaultHttpClient(); StringBuilder sb=new StringBuilder("myurl.com/pdf.php"); HttpPost mpost = new HttpPost(sb.toString()); String value = "1234"; List nameValuepairs = new ArrayList(1); nameValuepairs.add(new BasicNameValuePair("id",value)); mpost.setEntity(new UrlEncodedFormEntity(nameValuepairs)); } catch (UnsupportedEncodingException e) { Log.w(" error ", e.toString()); } catch (Exception e) { Log.w(" error ", e.toString()); } } And my php code to write the variable "value" onto the pdf document: //code to reverse the string if($_POST[] != null) { $reversed = strrev($_POST["value"]); $this->SetFont('Arial','u',50); $this->Text(52,68,$reversed); } I am just trying to write the variable in a random spot, but the variable the if statement is always null and I do not know why. Thanks. Sorry if it is a little sloppy.

    Read the article

  • Android while getting HTTP response to file how to know it wasn't fully loaded?

    - by Stan
    I'm using this approach to store a big-sized response from server to parse it later: final HttpClient client = new DefaultHttpClient(new BasicHttpParams()); final HttpGet mHttpGetRequest = new HttpGet(strUrl); mHttpGetRequest.setHeader("Content-Type", "application/x-www-form-urlencoded"); FileOutputStream fos = null; try { final HttpResponse response = client.execute(mHttpGetRequest); final StatusLine statusLine = response.getStatusLine(); lastHttpErrorCode = statusLine.getStatusCode(); lastHttpErrorMsg = statusLine.getReasonPhrase(); if (lastHttpErrorCode == 200) { HttpEntity entity = response.getEntity(); fos = new FileOutputStream(reponseFile); entity.writeTo(fos); entity.consumeContent(); fos.flush(); } } catch (ClientProtocolException e) { e.printStackTrace(); lastHttpErrorMsg = e.toString(); return null; } catch (final ParseException e) { e.printStackTrace(); lastHttpErrorMsg = e.toString(); return null; } catch (final UnknownHostException e) { e.printStackTrace(); lastHttpErrorMsg = e.toString(); return null; } catch (IOException e) { e.printStackTrace(); lastHttpErrorMsg = e.toString(); } finally{ if (fos!=null) try{ fos.close(); } catch (IOException e){} } now how could I ensure the response was completely received and thus saved to file? Assume client's device lost Internet connection while this code was running. So the app received only some part of real response. And I'm pretty sure it happens cuz I got parsing exceptions like "tag not closed", "unexpected end of file" etc. So I need to detect somehow this situation to prevent code from parsing partial response but can't see how. Is it possible at all and how to do it? Or has it has to raise IOException in such cases?

    Read the article

< Previous Page | 8 9 10 11 12 13 14  | Next Page >