Mined and Summarized Use Cases For API: commons-httpclient

  1. HTTP POST using JSON in Java

    None .. details

    1. String postUrl="www.site.com"
    2. // put in your urlGson gson= new Gson()
    3. HttpPost post = new HttpPost(postUrl)
    4. StringEntity postingString =new StringEntity(gson.toJson(pojo1))
    5. //convert your pojo to jsonpost.setEntity(postingString)
    6. post.setHeader("Content-type", "application/json")
    7. HttpResponse response = httpClient.execute(post)

  2. How to send a String array as basic name value pair as HTTPPOST?

    None .. details

    1. for (int i = 0
    2. i < type.length
    3. i++) { nameValuePairs.add(new BasicNameValuePair("type[]",type[i]))
    4. }

    • See Also (1)
    1. Passing String array to PHP as POST

      I'll give that a try now thanks . To pass an array to php in query string you should add to identifier and add every item as separate entry so something like this should work now POST['devices' on php side will contain an array. details

      Reactions - Positive 0, Negative 1, Others 0

      1. nameValuePairs.add(new BasicNameValuePair("devices[]", device1))
      2. nameValuePairs.add(new BasicNameValuePair("devices[]", device2))
      3. nameValuePairs.add(new BasicNameValuePair("devices[]", device3))

      Negative Reactions
      1. Hey, I am trying this but it isn't working, I don't know how to get Java to print out PHP errors so I am just getting an "Error executing script" message.
      Other Reactions
      1. I have updated my post with the code I am trying..

  3. Retrieve Data by passing a parameter to url in Android

    None .. details

    1. HttpGet get = new HttpGet(url)

    • See Also (4)
    1. How to handle HTTP timeout?

      Corrected it to catch both. Increase your time of waiting for response like . details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 )
      2. //1 minuteHttpConnectionParams.setSoTimeout( httpParameters, 90000 )
      3. // 1.5 minute

    2. Accessing JSON in using JSESSION ID or Authentication

      In HttpClient 3 this looks like this How to set the cookie in HttpClient 4 can be found here do-i-set-cookie-with-sessionid-for-post-request Apache-HttpClient-4.0.3 how-do-I-set-cookie-with-sessionID-for-POST-request Or you can take it a little bit lower level and add the full header. . details

      Reactions - Positive 4, Negative 1, Others 0

      1. HttpGet httpget = new HttpGet(url)
      2. httpget.addHeader("Cookie", "JSESSIONID=...")

      Positive Reactions
      1. For HttpClient 4 manually setting the cookie looks like this URL_http://stackoverflow.com/questions/4166129/apache-httpclient-4-0-3-how-do-i -set-cookie-with-sessionid-for-post-request.
      2. Thanks so much.
      3. So I can do something like method.setRequestHeader("Cookie", "JSESSIONID=F7B89109EABD2FFD58A0096AF2123199"); and it should work?
      4. Thanks.
      Negative Reactions
      1. I used Selenium to "login" then capture the JSESSION ID and pass that into my httpget.addHeader("Cookie", "JSESSIONID=" + jsessionIdVal);.
      Other Reactions
      1. This allowed me to get past the login screen.
      2. Ach, I see now that you ask for HttpClient 4.
      3. And how can I use HttpMethod and GetMethod?
      4. Not that it makes that much of a difference.
      5. The names I used are for HttpClient 3.
      6. I've seen this before but couldn't figure out what postData was in the question and answers.
      7. I already added the JAR files that I downloaded from Apache website you linked to but now sure what import to call.
      8. I've added it to the answer.

    3. HttpPost response doesn't return the json object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpResponse httpResponse = httpClient.execute(httpPost)
      2. if (httpResponse != null) { String resp = httpResponse.toString()

    4. JSON Object returns a null pointer

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. EntityUtils.toString(entity)

  4. When using JSON in Fragments the app is not responding in Android Development

    None .. details

    1. class TheTask extends AsyncTask<String, String, String> {
    2. @override
    3. protected String doInbackground(String... params) {
    4. String _response = null
    5. try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
    6. HttpPost httpPost = new HttpPost(params[0])
    7. HttpResponse httpResponse = httpClient.execute(httpPost)
    8. HttpEntity httpEntity = httpResponse.getEntity()
    9. _response = EntityUtils.toString(httpEntity)
    10. } catch (Exception e) {
    11. e.printStacktrace()
    12. }
    13. return _response
    14. }
    15. @Override
    16. protected void onPostExecute(
    17. String result) { // TODO Auto-generated method stub super.onPostExecute(result)
    18. Log.i(".......", result)
    19. }
    20. }

  5. When using JSON in Fragments the app is not responding in Android Development

    None .. details

    1. HttpResponse httpResponse = httpClient.execute(httpPost)

    • See Also (4)
    1. get JSON object from a HTTP response

      If you are supposed to get a JSON Object you can just put . Do this to get the JSON More details here from-httpresponse get-json-from-HttpResponse . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json = EntityUtils.toString(response.getEntity())

    2. A field of type "String" does not appear in the result (json) serialization of the vraptor controller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. result.use(Results.json()).indented().from(list) .include("codigoComposto").serialize()

    3. Empty exception when converting inputstream to JSONArrary

      Completely reinstalled my system including Windows 7) but still the same issue. I would first recommend that you change out all your stream monitoring code for the parser in the framework so the response block would become This might help guarantee you get all the correct data down from the server and properly formatted. details

      Reactions - Positive 1, Negative 1, Others 0

      1. HttpResponse response = httpClient.execute(request)
      2. String tekst = EntityUtils.toString( response.getEntity() )

      Positive Reactions
      1. Thanks for your response.
      Negative Reactions
      1. Unfortunately this gives the same JSONException.

    4. ProgressDialog is never dismissed when fetching JSON with AsyncTask

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String jsontext = EntityUtils.toString(response.getEntity())

  6. How to send a Json to a web service using HttpPost

    now try to understand the process how it works. Send string entity instead CODE This code will send json as string entity to server and receives HttpEntity as response . .. details

    1. HttpClient client = new DefaultHttpClient()
    2. HttpUriRequest request
    3. request = new HttpPost(<-URL->)
    4. StringEntity entity = new StringEntity(<-Your JSON string->)
    5. ((HttpPost) request).setEntity(entity)
    6. ((HttpPost) request).setHeader("Content-Type", "application/json")
    7. HttpResponse response = client.execute(request)
    8. HttpEntity entity = response.getEntity()

    Negative Reactions
    1. keep giving me the same error :(.
    2. i dont know what a stacktrace is, i feel really bad.
    3. Hi , i get an error in HttpResponse response client.execute(request); the error is a null pointer exception.
    Other Reactions
    1. ?
    2. can u send ur stacktrace??
    3. try using above code.
    4. tell me at which line are you getting a null pointer exception?

    • See Also (5)
    1. HTTP POST using JSON in Java

      momo's answer for Apache HttpClient version 4.3.1 or later. I'm using JSON Java to build my JSON object . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject()
      2. json.put("someKey", "someValue")
      3. CloseableHttpClient httpClient = HttpClientBuilder.create().build()
      4. try { HttpPost request = new HttpPost("http://yoururl")
      5. StringEntity params = new StringEntity(json.toString())
      6. request.addHeader("content-type", "application/x-www-form-urlencoded")
      7. request.setEntity(params)
      8. httpClient.execute(request)
      9. // handle response here...} catch (Exception ex) { // handle exception here} finally { httpClient.close()
      10. }

    2. Java: Gson and encoding

      The webserver could decode correctly those characters. By configuring the HttpClient for UTF encoding the problem disappeared here is my working code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpParams httpParams = new BasicHttpParams()
      2. HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8)
      3. HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8)
      4. HttpClient client = new DefaultHttpClient(httpParams)
      5. HttpPost request = new HttpPost(serverURL)
      6. StringEntity str = null
      7. String jsonString = gson.toJson(yourdata)
      8. str = new StringEntity(jsonString, HTTP.UTF_8)
      9. request.setEntity(str)
      10. request.setHeader("Accept", "application/json")
      11. request.setHeader("Content-type", "application/json")
      12. client.execute(request)

    3. how can a create a thread for a connection json call for android

      You shouldn't perform network operations in UI thread!For instance you can create AsyncTask in your class. It may looks similar to this After that simply call in onCreate method to start AsyncTask. details

      Reactions - Positive 1, Negative 0, Others 0

      1. private class ParseTask extends AsyncTask<Params, Progress, Result> {
      2. @Override
      3. protected Result doInBackground(Params params) { // get url Params url = params[0]
      4. // create HttpClient etc. ... // get response, and parse json // return return result
      5. }
      6. @Override
      7. protected void onPostExecute(
      8. Result
      9. result) { // now when you have result from parsed json, // update application UI or whatever you need someEditText.setText(value_from_result)
      10. }
      11. }

      Positive Reactions
      1. this work great, thanx...

    4. How can I read MYSQL Database from Android?

      Thank you again!. This should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.Online.Test
      2. import java.io.IOException
      3. import org.apache.http.HttpEntity
      4. import org.apache.http.HttpResponse
      5. import org.apache.http.client.ClientProtocolException
      6. import org.apache.http.client.HttpClient
      7. import org.apache.http.client.methods.HttpPost
      8. import org.apache.http.impl.client.DefaultHttpClient
      9. import org.apache.http.util.EntityUtils
      10. import org.json.JSONArray
      11. import org.json.JSONException
      12. import org.json.JSONObject
      13. import android.app.Activity
      14. import android.os.AsyncTask
      15. import android.os.Bundle
      16. import android.widget.TextView
      17. import android.widget.Toast
      18. public class OnlineTestActivity extends Activity { /** Called when the activity is first created. */ TextView resultView
      19. HttpClient client
      20. JSONObject json
      21. String Dat
      22. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
      23. setContentView(R.layout.main)
      24. resultView = (TextView) findViewById(R.id.tvjson)
      25. client = new DefaultHttpClient()
      26. try { json = RedData()
      27. } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
      28. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      29. } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
      30. } Dat = json.toString()
      31. new Read().onPostExecute(Dat)
      32. } public JSONObject RedData() throws ClientProtocolException, IOException, JSONException { HttpPost httppost = new HttpPost("//link.php")
      33. HttpResponse r = client.execute(httppost)
      34. // int status = r.getStatusLine().getStatusCode()
      35. //if (status == 200) { HttpEntity e = r.getEntity()
      36. String data = EntityUtils.toString(e)
      37. JSONArray jArray = new JSONArray(data)
      38. JSONObject last = jArray.getJSONObject(0)
      39. // 0 -> the last object return last
      40. // } else { // Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG)
      41. // return null
      42. //} } public class Read extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { json = RedData()
      43. //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG)
      44. return json.getString(arg0[0])
      45. } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
      46. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      47. } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
      48. } return null
      49. } @Override protected void onPostExecute(String data) { // TODO Auto-generated method stub resultView.setText(data)
      50. } }}

      Other Reactions
      1. It would be even better if you explained the code and/or corrections.

    5. HTTP POST using JSON in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpClient httpClient = new DefaultHttpClient()
      2. try { HttpPost request = new HttpPost("http://yoururl")
      3. StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ")
      4. request.addHeader("content-type", "application/x-www-form-urlencoded")
      5. request.setEntity(params)
      6. HttpResponse response = httpClient.execute(request)
      7. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      8. }

  7. Parsing Twitter API 1.1 JSON

    You forgot to close the ProgressDialog in onPostExecute method.just do this in onPostExecute like this. . .. details

    1. @Overrideprotected void onPostExecute(Integer result) { pd.dismiss()
    2. // Extract Token from JSON stream try { JSONObject root = new JSONObject(jsonTokenStream)
    3. twitterToken = root.getString("access_token")
    4. } catch (Exception e) { Log.e("loadTwitterToken", "onPost Error:" + e.getMessage())
    5. } twitterText.setText("Got Token!")
    6. // Now that we have a oAuth Token, lets get our JSON feed from twitter. // We call it from here to make sure the Token has been received already. new loadTwitterFeed().execute()
    7. }

    Positive Reactions
    1. I've made strides in the code.
    2. +1 save my lots of search and time..
    3. Thanks for that @Priyanka.
    4. So it has authorized properly, but stops there.
    5. I appreciate your help so far.
    6. Thanks for the explanation @Priyanka!
    7. The only problem I'm having now is getting the R.java file to create an android.R.id.list, but my ListView id seems fine: "android:id="@android:id/list" Could anything else be causing it not to generate?
    Negative Reactions
    1. Again, it still doesn't crash or show errors, but I get as far as the status telling me "Got Token!"
    2. It should be the last blocks in the file.
    3. @reekdev when R.java file is not created than probably the error is in res folder.Check all .xml files if any error is there , also check your imports packages is there any package name 'android.R' remove it and if you use 'android:id="@android:id/list' means implicit android list than you should extends your class with ListActivity.
    4. I've found that I needed to change the XML TextView to ListView and drop the ScrollView.
    Other Reactions
    1. Can you tell if I set up the parse properly to output a list of tweets from my updated java?
    2. I can tell I'm close.
    3. I've made a few updates to the code.

  8. How to make a &quot;raw&quot; string out of JSON in Java

    None .. details

    1. public static JSONArray getJSONArrayFromURL(String url) { // initialize InputStream is = null
    2. String result = ""
    3. JSONArray jArray = null
    4. Log.d("URL_SEARCH", url)
    5. // http post try { HttpClient httpclient = new DefaultHttpClient()
    6. HttpPost httppost = new HttpPost(url)
    7. HttpResponse response = httpclient.execute(httppost)
    8. HttpEntity entity = response.getEntity()
    9. is = entity.getContent()
    10. } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString())
    11. } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8)
    12. StringBuilder sb = new StringBuilder()
    13. String line = null
    14. while ((line = reader.readLine()) != null) { sb.append(line + "\n")
    15. } is.close()
    16. result = sb.toString()
    17. } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString())
    18. } // try parse the string to a JSON object try { jArray = new JSONArray(result)
    19. Log.d("URL_SEARCH", "JSON: " + jArray.length())
    20. } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString())
    21. } return jArray
    22. }

  9. How to fetch data of API through JSONArray

    TharakaNirmana-Please help me for fetching path of image its urgent work for me. Step 1 copy the WEBSERVICE URL and paste in to your browser this will hit the web service and will show you the response use chrome will be more helpful to see the JSON response Step 2 analyse the structure of your JSON responsefirst of all you will be reading the complete response as a String create a JSON OBJECT from the String now convert that JSON object into a JSONARRAY object now that you have a JSONARRAY iterate the JSON Array and store one by one Object inside the iteration loop for JSON array for each JSON OBJECT call the value by their namesee in JSON you have key value pairs you can call JSONOBJECT.getString("variable name which retrieves String or you can get other datatypes like this also try this on your own post me the status will be responding you with modified code afterwards I tried to resolve it for you here is the class see the first method is the same as you wrote itin the second method i am trying to traverse the JSON response step by step.see you have to be careful about your JSON response 1 your complete response is a JSON OBJECT 2 if any element is written like this is a JSON Object 3 if any element is writen like this is value inside you json object which you can get by 4 if any element is writen like then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by and then you can traverse the elements of the JSON ARRAY by now you can traverse and retrieve the value you want post me if any help needed further . .. details

    1. package com.hussain.StackOverFlow
    2. import java.io.BufferedReader
    3. import java.io.InputStream
    4. import java.io.InputStreamReader
    5. import java.net.URI
    6. import java.util.ArrayList
    7. import org.apache.http.HttpResponse
    8. import org.apache.http.client.HttpClient
    9. import org.apache.http.client.methods.HttpGet
    10. import org.apache.http.impl.client.DefaultHttpClient
    11. import org.apache.http.params.HttpConnectionParams
    12. import org.apache.http.params.HttpParams
    13. import org.json.JSONArray
    14. import org.json.JSONException
    15. import org.json.JSONObject
    16. public class FarhaSameer1 { public static void main(String[] args) { String asd = FarhaSameer1.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb")
    17. FarhaSameer1.parseFromJSONResponse(asd)
    18. } // API link // http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb // String Method to fetech data from server public static String sendRequest(String url) { String result = ""
    19. try { HttpClient client = new DefaultHttpClient()
    20. HttpParams httpParameters = client.getParams()
    21. HttpConnectionParams.setConnectionTimeout(httpParameters, 5000)
    22. HttpConnectionParams.setSoTimeout(httpParameters, 5000)
    23. HttpConnectionParams.setTcpNoDelay(httpParameters, true)
    24. HttpGet request = new HttpGet()
    25. request.setURI(new URI(url))
    26. HttpResponse response = client.execute(request)
    27. InputStream ips = response.getEntity().getContent()
    28. BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"))
    29. StringBuilder sb = new StringBuilder()
    30. String s
    31. while (true) { s = buf.readLine()
    32. if (s == null || s.length() == 0) break
    33. sb.append(s)
    34. } buf.close()
    35. ips.close()
    36. result = sb.toString()
    37. } catch (Exception e) { e.printStackTrace()
    38. } return result
    39. } public static void parseFromJSONResponse(String respo) { JSONObject myjson
    40. try { myjson = new JSONObject(respo)
    41. JSONObject jsonObj1 = myjson.getJSONObject("feed")
    42. JSONArray jsonObj2 = jsonObj1.getJSONArray("entry")
    43. JSONObject jsonObj3 = jsonObj2.getJSONObject(0)
    44. System.out.println(jsonObj3.getJSONObject("content"))
    45. System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString())
    46. } catch (JSONException e) { e.printStackTrace()
    47. } } }

    Negative Reactions
    1. a little help is here , URL_http://stackoverflow.com/questions/16544388 /converting-jsonarray-string-to-array/16544515#16544515.
    Other Reactions
    1. ?
    2. @FarhaSameer : was it enough ?

    • See Also (1)
    1. Error with JSON data Android Illegal Argument HttpClient

      In this you can also pass your required parameters. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. import java.io.BufferedReader
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.io.InputStreamReader
      5. import java.net.URLEncoder
      6. import java.util.ArrayList
      7. import org.apache.http.HttpEntity
      8. import org.apache.http.HttpResponse
      9. import org.apache.http.NameValuePair
      10. import org.apache.http.client.ClientProtocolException
      11. import org.apache.http.client.HttpClient
      12. import org.apache.http.client.entity.UrlEncodedFormEntity
      13. import org.apache.http.client.methods.HttpGet
      14. import org.apache.http.client.methods.HttpPost
      15. import org.apache.http.client.methods.HttpUriRequest
      16. import org.apache.http.impl.client.DefaultHttpClient
      17. import org.apache.http.message.BasicNameValuePair
      18. import org.apache.http.protocol.HTTP
      19. import org.json.JSONException
      20. import org.json.JSONObject
      21. public class JsonClient { public enum RequestMethod{ GET, POST } private ArrayList <NameValuePair> params
      22. private ArrayList <NameValuePair> headers
      23. private String url
      24. private int responseCode
      25. private String message
      26. private JSONObject jsonResponse
      27. public JSONObject getResponse() { return jsonResponse
      28. } public String getErrorMessage() { return message
      29. } public int getResponseCode() { return responseCode
      30. } public JsonClient(String url) { this.url = url
      31. params = new ArrayList<NameValuePair>()
      32. headers = new ArrayList<NameValuePair>()
      33. } public void addParam(String name, String value) { params.add(new BasicNameValuePair(name, value))
      34. } public void addHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value))
      35. } public void execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""
      36. if(!params.isEmpty()){ combinedParams += "?"
      37. for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8")
      38. if(combinedParams.length() > 1) { combinedParams += "&" + paramString
      39. } else { combinedParams += paramString
      40. } } } HttpGet request = new HttpGet(url + combinedParams)
      41. //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
      42. } executeRequest(request, url)
      43. break
      44. } case POST: { HttpPost request = new HttpPost(url)
      45. //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
      46. } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8))
      47. } executeRequest(request, url)
      48. break
      49. } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient()
      50. HttpResponse httpResponse
      51. try { httpResponse = client.execute(request)
      52. responseCode = httpResponse.getStatusLine().getStatusCode()
      53. message = httpResponse.getStatusLine().getReasonPhrase()
      54. HttpEntity entity = httpResponse.getEntity()
      55. if (entity != null) { InputStream instream = entity.getContent()
      56. String response = convertStreamToString(instream)
      57. jsonResponse = new JSONObject(response)
      58. // Closing the input stream will trigger connection release instream.close()
      59. } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown()
      60. e.printStackTrace()
      61. } catch (IOException e) { client.getConnectionManager().shutdown()
      62. e.printStackTrace()
      63. }catch (JSONException e) { e.printStackTrace()
      64. } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is))
      65. StringBuilder sb = new StringBuilder()
      66. String line = null
      67. try { while ((line = reader.readLine()) != null) { sb.append(line + "\n")
      68. } } catch (IOException e) { e.printStackTrace()
      69. } finally { try { is.close()
      70. } catch (IOException e) { e.printStackTrace()
      71. } } return sb.toString()
      72. }}

      Positive Reactions
      1. Thanks for this.
      Other Reactions
      1. I'll be able to use this in the future for sure.

  10. simplest way to read json from a URL in java

    construct a JSON object with this string more at json.org . hi friends i done the json parser in simplest way here it is this class returns the json object from the url and when you want the json object you just call this class and the method in it your activity class my code is here here the json key is denoted that the key in your json file this is a simple json file example json":"hi" here json is key and hi is value this will get your json value to string contentthank you . .. details

    1. package com.inzane.shoapp.activity
    2. import java.io.BufferedReader
    3. import java.io.IOException
    4. import java.io.InputStream
    5. import java.io.InputStreamReader
    6. import java.io.UnsupportedEncodingException
    7. import org.apache.http.HttpEntity
    8. import org.apache.http.HttpResponse
    9. import org.apache.http.client.ClientProtocolException
    10. import org.apache.http.client.methods.HttpPost
    11. import org.apache.http.impl.client.DefaultHttpClient
    12. import org.json.JSONException
    13. import org.json.JSONObject
    14. import android.util.Log
    15. public class JSONParser {static InputStream is = null
    16. static JSONObject jObj = null
    17. static String json = ""
    18. // constructorpublic JSONParser() {}public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
    19. HttpPost httpPost = new HttpPost(url)
    20. HttpResponse httpResponse = httpClient.execute(httpPost)
    21. HttpEntity httpEntity = httpResponse.getEntity()
    22. is = httpEntity.getContent()
    23. } catch (UnsupportedEncodingException e) { e.printStackTrace()
    24. } catch (ClientProtocolException e) { e.printStackTrace()
    25. } catch (IOException e) { e.printStackTrace()
    26. } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8)
    27. StringBuilder sb = new StringBuilder()
    28. String line = null
    29. while ((line = reader.readLine()) != null) { sb.append(line + "\n")
    30. System.out.println(line)
    31. } is.close()
    32. json = sb.toString()
    33. } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString())
    34. } // try parse the string to a JSON object try { jObj = new JSONObject(json)
    35. } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString())
    36. System.out.println("error on parse data in jsonparser.java")
    37. } // return JSON String return jObj
    38. }}

  11. JSONArray cannot be converted to JSONObject given a string

    None .. details

    1. ... public JSONObject getJSONfromURL (String url){ //HTTP call try{ URLConnection connection = new URL(url).openConnection()
    2. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16)
    3. StringBuffer builder = new StringBuffer()
    4. String line
    5. while ((line = reader.readLine()) != null) { builder.append(line).append("\n")
    6. } String blah = builder.toString()
    7. //Parsing string into JSONArray JSONArray data = new JSONArray(new String(blah))
    8. for(int i=0
    9. i < data.length()
    10. i++) { object = data.getJSONObject(i)
    11. String id = object.getString("id")
    12. String value = object.getString("name")
    13. Log.d("Item name: ", value)
    14. } } catch(Exception e){ Log.e("Http Error","Error in http connection " + e.toString())
    15. } return object
    16. }..

  12. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

    It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . .. details

    1. import org.apache.http.HttpResponse
    2. import org.apache.http.client.HttpClient
    3. import org.apache.http.client.methods.HttpPut
    4. import org.apache.http.entity.StringEntity
    5. import org.apache.http.impl.client.DefaultHttpClient
    6. import net.sf.json.JSONArray
    7. import net.sf.json.JSONObject
    8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
    9. for (int i = 0
    10. i < 5
    11. i++) { JSONObject jsonAddressObj = new JSONObject()
    12. jsonAddressObj.put("address1", "a")
    13. jsonAddressObj.put("address2", "b")
    14. jsonAddressObj.put("city", "c")
    15. jsonAddressObj.put("state", "d")
    16. jsonAddressObj.put("postalCode", "e")
    17. jsonAddressArray.add(jsonAddressObj)
    18. } System.out.println(jsonAddressArray)
    19. HttpClient httpClient = new DefaultHttpClient()
    20. try { HttpPut request = new HttpPut("http://yourAddressHere")
    21. StringEntity params =new StringEntity(jsonAddressArray.toString())
    22. request.setEntity(params)
    23. HttpResponse response = httpClient.execute(request)
    24. System.out.println(response.toString())
    25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
    26. }}

    Positive Reactions
    1. Thanks, and it's good your pointing that out.
    2. But +1 for everything else!.
    3. I just put the values to my jsonAddressObj.
    4. I do not want to send harcoded values to any of the fields.
    5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
    Other Reactions
    1. OK.
    2. I need to send the following as http request.
    3. Yeh, I got the feeling we're not using the same library.
    4. I did take out the for loop.
    5. That helped me.
    6. I want the address to be fetched from the EditText.
    7. That is the reason i used txtAddress1.getText().toString().
    8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
    9. Have you read anything about these technologies or checked the documentation?
    10. That did that work for me.
    11. Are you referring to a post or a put ?
    12. Is it just me or you're never adding anything to your jsonAddressArray ?
    13. Passed the jsonAddressObj to jsonObjSend.
    14. Http request is quite broad.
    15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
    16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
    17. Here is what I want to do.
    18. it is a put method.
    19. Yeh your right...it's from the original code.

  13. Android JSON api trouble with PUT operations

    First important)** you need to determine if your request was successful prior to processing the response body. Given the structure of your code I would recommend declaring a status code variable at the beginning of your retrieval method and setting it after each execute Second important)** you need to check that your response entity is non null before calling any methods on it. .. details

    1. HttpResponse httpResponse = httpClient.execute(httpPut)
    2. status = httpResponse.getStatusLine().getStatusCode()

    • See Also (1)
    1. process in-app apple receipt with java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES)

  14. Get jSON Response for POST

    If you have the Log please paste it in your question and also please update your question with the new code. Here what you need to do . .. details

    1. HttpResponse mHttpResponse = mHttpClient.execute(httppost)
    2. StatusLine status = mHttpResponse.getStatusLine()
    3. int response = status.getStatusCode()

    • See Also (2)
    1. Get jSON Response for POST

      Hop it will help you. This is what you need . details

      Reactions - Positive 2, Negative 0, Others 0

      1. String jsonString = EntityUtils.toString(response.getEntity())

      Positive Reactions
      1. I have tried implementing you code ANR !!!
      2. If you have the Log please paste it in your question and also please update your question with the new code.
      Other Reactions
      1. !.
      2. You must implement the Http code in AsyncTask because it is network code.

    2. Using HttpClient and HttpPost in Android with post parameters

      Thanks for the help. I've just checked and i have the same code as you and it works perferctly.The only difference is how i fill my List for the params I use a ArrayList<BasicNameValuePair params and fill it this way I do not use any JSONObject to send params to the webservices. details

      Reactions - Positive 1, Negative 0, Others 0

      1. params.add(new BasicNameValuePair("apikey", apikey)

      Positive Reactions
      1. Since I'm working in parallell with an Iphone developer, and his app actually posts data, I have no other choice than also submitting data as JSON.
      Other Reactions
      1. I tried sending just the two valuepairs, but no difference.

  15. Connect to a MySQL database from android. No indication it&#39;s working/not working...?

    Take a look on this link greater-in-android HTTP-Client-API-level-11-or-greater-in-Android . Also for the POST request I think that you can use this code . .. details

    1. public String post(String str) { String result = ""
    2. try { HttpParams httpParameters = new BasicHttpParams()
    3. int timeoutConnection = 3000
    4. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection)
    5. int timeoutSocket = 5000
    6. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket)
    7. DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters)
    8. HttpPost postRequest = new HttpPost(SERVER_ADDRESS)
    9. StringEntity input = new StringEntity(str)
    10. input.setContentType("application/json")
    11. postRequest.setEntity(input)
    12. HttpResponse response = httpClient.execute(postRequest)
    13. result = getResult(response).toString()
    14. httpClient.getConnectionManager().shutdown()
    15. } catch (Exception e) { System.out.println(e.getMessage())
    16. } return result
    17. }private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException { StringBuilder result = new StringBuilder()
    18. BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024)
    19. String output
    20. while ((output = br.readLine()) != null) result.append(output)
    21. return result
    22. }

    Positive Reactions
    1. Thanks, didn't think about having this going in the background via threads.
    2. You are welcome.
    3. Thanks for the code too.
    4. hope that it is helpful for you.
    Other Reactions
    1. That will have to be implemented.

    • See Also (1)
    1. Android - Connecting to MySQL database

      Insert following line below TextView txt Below rootLayout.addView(txt) insert following two lines Now modify this line nameValuePairs.add(new BasicNameValuePair("name","tom")) to fetch value from the EditText. You can also create one for year. details

      Reactions - Positive 0, Negative 0, Others 0

      1. nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()))

  1. cookiepolicy
      Chart will be rendered here
    1. process in-app apple receipt with java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES)

  2. httpclient
      Chart will be rendered here
    1. How to send a Json to a web service using HttpPost

      now try to understand the process how it works. Send string entity instead CODE This code will send json as string entity to server and receives HttpEntity as response . details

      Reactions - Positive 0, Negative 3, Others 0

      1. HttpClient client = new DefaultHttpClient()
      2. HttpUriRequest request
      3. request = new HttpPost(<-URL->)
      4. StringEntity entity = new StringEntity(<-Your JSON string->)
      5. ((HttpPost) request).setEntity(entity)
      6. ((HttpPost) request).setHeader("Content-Type", "application/json")
      7. HttpResponse response = client.execute(request)
      8. HttpEntity entity = response.getEntity()

      Negative Reactions
      1. keep giving me the same error :(.
      2. i dont know what a stacktrace is, i feel really bad.
      3. Hi , i get an error in HttpResponse response client.execute(request); the error is a null pointer exception.
      Other Reactions
      1. ?
      2. can u send ur stacktrace??
      3. try using above code.
      4. tell me at which line are you getting a null pointer exception?

    2. Java: Gson and encoding

      The webserver could decode correctly those characters. By configuring the HttpClient for UTF encoding the problem disappeared here is my working code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpParams httpParams = new BasicHttpParams()
      2. HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8)
      3. HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8)
      4. HttpClient client = new DefaultHttpClient(httpParams)
      5. HttpPost request = new HttpPost(serverURL)
      6. StringEntity str = null
      7. String jsonString = gson.toJson(yourdata)
      8. str = new StringEntity(jsonString, HTTP.UTF_8)
      9. request.setEntity(str)
      10. request.setHeader("Accept", "application/json")
      11. request.setHeader("Content-type", "application/json")
      12. client.execute(request)

    3. How to make a "raw" string out of JSON in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static JSONArray getJSONArrayFromURL(String url) { // initialize InputStream is = null
      2. String result = ""
      3. JSONArray jArray = null
      4. Log.d("URL_SEARCH", url)
      5. // http post try { HttpClient httpclient = new DefaultHttpClient()
      6. HttpPost httppost = new HttpPost(url)
      7. HttpResponse response = httpclient.execute(httppost)
      8. HttpEntity entity = response.getEntity()
      9. is = entity.getContent()
      10. } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString())
      11. } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8)
      12. StringBuilder sb = new StringBuilder()
      13. String line = null
      14. while ((line = reader.readLine()) != null) { sb.append(line + "\n")
      15. } is.close()
      16. result = sb.toString()
      17. } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString())
      18. } // try parse the string to a JSON object try { jArray = new JSONArray(result)
      19. Log.d("URL_SEARCH", "JSON: " + jArray.length())
      20. } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString())
      21. } return jArray
      22. }

    4. HTTP POST using JSON in Java

      momo's answer for Apache HttpClient version 4.3.1 or later. I'm using JSON Java to build my JSON object . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = new JSONObject()
      2. json.put("someKey", "someValue")
      3. CloseableHttpClient httpClient = HttpClientBuilder.create().build()
      4. try { HttpPost request = new HttpPost("http://yoururl")
      5. StringEntity params = new StringEntity(json.toString())
      6. request.addHeader("content-type", "application/x-www-form-urlencoded")
      7. request.setEntity(params)
      8. httpClient.execute(request)
      9. // handle response here...} catch (Exception ex) { // handle exception here} finally { httpClient.close()
      10. }

    5. How can I read MYSQL Database from Android?

      Thank you again!. This should work . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.Online.Test
      2. import java.io.IOException
      3. import org.apache.http.HttpEntity
      4. import org.apache.http.HttpResponse
      5. import org.apache.http.client.ClientProtocolException
      6. import org.apache.http.client.HttpClient
      7. import org.apache.http.client.methods.HttpPost
      8. import org.apache.http.impl.client.DefaultHttpClient
      9. import org.apache.http.util.EntityUtils
      10. import org.json.JSONArray
      11. import org.json.JSONException
      12. import org.json.JSONObject
      13. import android.app.Activity
      14. import android.os.AsyncTask
      15. import android.os.Bundle
      16. import android.widget.TextView
      17. import android.widget.Toast
      18. public class OnlineTestActivity extends Activity { /** Called when the activity is first created. */ TextView resultView
      19. HttpClient client
      20. JSONObject json
      21. String Dat
      22. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
      23. setContentView(R.layout.main)
      24. resultView = (TextView) findViewById(R.id.tvjson)
      25. client = new DefaultHttpClient()
      26. try { json = RedData()
      27. } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
      28. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      29. } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
      30. } Dat = json.toString()
      31. new Read().onPostExecute(Dat)
      32. } public JSONObject RedData() throws ClientProtocolException, IOException, JSONException { HttpPost httppost = new HttpPost("//link.php")
      33. HttpResponse r = client.execute(httppost)
      34. // int status = r.getStatusLine().getStatusCode()
      35. //if (status == 200) { HttpEntity e = r.getEntity()
      36. String data = EntityUtils.toString(e)
      37. JSONArray jArray = new JSONArray(data)
      38. JSONObject last = jArray.getJSONObject(0)
      39. // 0 -> the last object return last
      40. // } else { // Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG)
      41. // return null
      42. //} } public class Read extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { json = RedData()
      43. //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG)
      44. return json.getString(arg0[0])
      45. } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
      46. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
      47. } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
      48. } return null
      49. } @Override protected void onPostExecute(String data) { // TODO Auto-generated method stub resultView.setText(data)
      50. } }}

      Other Reactions
      1. It would be even better if you explained the code and/or corrections.

    6. HTTP POST using JSON in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpClient httpClient = new DefaultHttpClient()
      2. try { HttpPost request = new HttpPost("http://yoururl")
      3. StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ")
      4. request.addHeader("content-type", "application/x-www-form-urlencoded")
      5. request.setEntity(params)
      6. HttpResponse response = httpClient.execute(request)
      7. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      8. }

    7. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

      It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

      Reactions - Positive 5, Negative 0, Others 0

      1. import org.apache.http.HttpResponse
      2. import org.apache.http.client.HttpClient
      3. import org.apache.http.client.methods.HttpPut
      4. import org.apache.http.entity.StringEntity
      5. import org.apache.http.impl.client.DefaultHttpClient
      6. import net.sf.json.JSONArray
      7. import net.sf.json.JSONObject
      8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
      9. for (int i = 0
      10. i < 5
      11. i++) { JSONObject jsonAddressObj = new JSONObject()
      12. jsonAddressObj.put("address1", "a")
      13. jsonAddressObj.put("address2", "b")
      14. jsonAddressObj.put("city", "c")
      15. jsonAddressObj.put("state", "d")
      16. jsonAddressObj.put("postalCode", "e")
      17. jsonAddressArray.add(jsonAddressObj)
      18. } System.out.println(jsonAddressArray)
      19. HttpClient httpClient = new DefaultHttpClient()
      20. try { HttpPut request = new HttpPut("http://yourAddressHere")
      21. StringEntity params =new StringEntity(jsonAddressArray.toString())
      22. request.setEntity(params)
      23. HttpResponse response = httpClient.execute(request)
      24. System.out.println(response.toString())
      25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      26. }}

      Positive Reactions
      1. Thanks, and it's good your pointing that out.
      2. But +1 for everything else!.
      3. I just put the values to my jsonAddressObj.
      4. I do not want to send harcoded values to any of the fields.
      5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
      Other Reactions
      1. OK.
      2. I need to send the following as http request.
      3. Yeh, I got the feeling we're not using the same library.
      4. I did take out the for loop.
      5. That helped me.
      6. I want the address to be fetched from the EditText.
      7. That is the reason i used txtAddress1.getText().toString().
      8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
      9. Have you read anything about these technologies or checked the documentation?
      10. That did that work for me.
      11. Are you referring to a post or a put ?
      12. Is it just me or you're never adding anything to your jsonAddressArray ?
      13. Passed the jsonAddressObj to jsonObjSend.
      14. Http request is quite broad.
      15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
      16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
      17. Here is what I want to do.
      18. it is a put method.
      19. Yeh your right...it's from the original code.

    8. Error with JSON data Android Illegal Argument HttpClient

      In this you can also pass your required parameters. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. import java.io.BufferedReader
      2. import java.io.IOException
      3. import java.io.InputStream
      4. import java.io.InputStreamReader
      5. import java.net.URLEncoder
      6. import java.util.ArrayList
      7. import org.apache.http.HttpEntity
      8. import org.apache.http.HttpResponse
      9. import org.apache.http.NameValuePair
      10. import org.apache.http.client.ClientProtocolException
      11. import org.apache.http.client.HttpClient
      12. import org.apache.http.client.entity.UrlEncodedFormEntity
      13. import org.apache.http.client.methods.HttpGet
      14. import org.apache.http.client.methods.HttpPost
      15. import org.apache.http.client.methods.HttpUriRequest
      16. import org.apache.http.impl.client.DefaultHttpClient
      17. import org.apache.http.message.BasicNameValuePair
      18. import org.apache.http.protocol.HTTP
      19. import org.json.JSONException
      20. import org.json.JSONObject
      21. public class JsonClient { public enum RequestMethod{ GET, POST } private ArrayList <NameValuePair> params
      22. private ArrayList <NameValuePair> headers
      23. private String url
      24. private int responseCode
      25. private String message
      26. private JSONObject jsonResponse
      27. public JSONObject getResponse() { return jsonResponse
      28. } public String getErrorMessage() { return message
      29. } public int getResponseCode() { return responseCode
      30. } public JsonClient(String url) { this.url = url
      31. params = new ArrayList<NameValuePair>()
      32. headers = new ArrayList<NameValuePair>()
      33. } public void addParam(String name, String value) { params.add(new BasicNameValuePair(name, value))
      34. } public void addHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value))
      35. } public void execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""
      36. if(!params.isEmpty()){ combinedParams += "?"
      37. for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8")
      38. if(combinedParams.length() > 1) { combinedParams += "&" + paramString
      39. } else { combinedParams += paramString
      40. } } } HttpGet request = new HttpGet(url + combinedParams)
      41. //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
      42. } executeRequest(request, url)
      43. break
      44. } case POST: { HttpPost request = new HttpPost(url)
      45. //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
      46. } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8))
      47. } executeRequest(request, url)
      48. break
      49. } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient()
      50. HttpResponse httpResponse
      51. try { httpResponse = client.execute(request)
      52. responseCode = httpResponse.getStatusLine().getStatusCode()
      53. message = httpResponse.getStatusLine().getReasonPhrase()
      54. HttpEntity entity = httpResponse.getEntity()
      55. if (entity != null) { InputStream instream = entity.getContent()
      56. String response = convertStreamToString(instream)
      57. jsonResponse = new JSONObject(response)
      58. // Closing the input stream will trigger connection release instream.close()
      59. } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown()
      60. e.printStackTrace()
      61. } catch (IOException e) { client.getConnectionManager().shutdown()
      62. e.printStackTrace()
      63. }catch (JSONException e) { e.printStackTrace()
      64. } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is))
      65. StringBuilder sb = new StringBuilder()
      66. String line = null
      67. try { while ((line = reader.readLine()) != null) { sb.append(line + "\n")
      68. } } catch (IOException e) { e.printStackTrace()
      69. } finally { try { is.close()
      70. } catch (IOException e) { e.printStackTrace()
      71. } } return sb.toString()
      72. }}

      Positive Reactions
      1. Thanks for this.
      Other Reactions
      1. I'll be able to use this in the future for sure.

    9. How to fetch data of API through JSONArray

      TharakaNirmana-Please help me for fetching path of image its urgent work for me. Step 1 copy the WEBSERVICE URL and paste in to your browser this will hit the web service and will show you the response use chrome will be more helpful to see the JSON response Step 2 analyse the structure of your JSON responsefirst of all you will be reading the complete response as a String create a JSON OBJECT from the String now convert that JSON object into a JSONARRAY object now that you have a JSONARRAY iterate the JSON Array and store one by one Object inside the iteration loop for JSON array for each JSON OBJECT call the value by their namesee in JSON you have key value pairs you can call JSONOBJECT.getString("variable name which retrieves String or you can get other datatypes like this also try this on your own post me the status will be responding you with modified code afterwards I tried to resolve it for you here is the class see the first method is the same as you wrote itin the second method i am trying to traverse the JSON response step by step.see you have to be careful about your JSON response 1 your complete response is a JSON OBJECT 2 if any element is written like this is a JSON Object 3 if any element is writen like this is value inside you json object which you can get by 4 if any element is writen like then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by and then you can traverse the elements of the JSON ARRAY by now you can traverse and retrieve the value you want post me if any help needed further . details

      Reactions - Positive 0, Negative 1, Others 0

      1. package com.hussain.StackOverFlow
      2. import java.io.BufferedReader
      3. import java.io.InputStream
      4. import java.io.InputStreamReader
      5. import java.net.URI
      6. import java.util.ArrayList
      7. import org.apache.http.HttpResponse
      8. import org.apache.http.client.HttpClient
      9. import org.apache.http.client.methods.HttpGet
      10. import org.apache.http.impl.client.DefaultHttpClient
      11. import org.apache.http.params.HttpConnectionParams
      12. import org.apache.http.params.HttpParams
      13. import org.json.JSONArray
      14. import org.json.JSONException
      15. import org.json.JSONObject
      16. public class FarhaSameer1 { public static void main(String[] args) { String asd = FarhaSameer1.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb")
      17. FarhaSameer1.parseFromJSONResponse(asd)
      18. } // API link // http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb // String Method to fetech data from server public static String sendRequest(String url) { String result = ""
      19. try { HttpClient client = new DefaultHttpClient()
      20. HttpParams httpParameters = client.getParams()
      21. HttpConnectionParams.setConnectionTimeout(httpParameters, 5000)
      22. HttpConnectionParams.setSoTimeout(httpParameters, 5000)
      23. HttpConnectionParams.setTcpNoDelay(httpParameters, true)
      24. HttpGet request = new HttpGet()
      25. request.setURI(new URI(url))
      26. HttpResponse response = client.execute(request)
      27. InputStream ips = response.getEntity().getContent()
      28. BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"))
      29. StringBuilder sb = new StringBuilder()
      30. String s
      31. while (true) { s = buf.readLine()
      32. if (s == null || s.length() == 0) break
      33. sb.append(s)
      34. } buf.close()
      35. ips.close()
      36. result = sb.toString()
      37. } catch (Exception e) { e.printStackTrace()
      38. } return result
      39. } public static void parseFromJSONResponse(String respo) { JSONObject myjson
      40. try { myjson = new JSONObject(respo)
      41. JSONObject jsonObj1 = myjson.getJSONObject("feed")
      42. JSONArray jsonObj2 = jsonObj1.getJSONArray("entry")
      43. JSONObject jsonObj3 = jsonObj2.getJSONObject(0)
      44. System.out.println(jsonObj3.getJSONObject("content"))
      45. System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString())
      46. } catch (JSONException e) { e.printStackTrace()
      47. } } }

      Negative Reactions
      1. a little help is here , URL_http://stackoverflow.com/questions/16544388 /converting-jsonarray-string-to-array/16544515#16544515.
      Other Reactions
      1. ?
      2. @FarhaSameer : was it enough ?

    10. how can a create a thread for a connection json call for android

      You shouldn't perform network operations in UI thread!For instance you can create AsyncTask in your class. It may looks similar to this After that simply call in onCreate method to start AsyncTask. details

      Reactions - Positive 1, Negative 0, Others 0

      1. private class ParseTask extends AsyncTask<Params, Progress, Result> {
      2. @Override
      3. protected Result doInBackground(Params params) { // get url Params url = params[0]
      4. // create HttpClient etc. ... // get response, and parse json // return return result
      5. }
      6. @Override
      7. protected void onPostExecute(
      8. Result
      9. result) { // now when you have result from parsed json, // update application UI or whatever you need someEditText.setText(value_from_result)
      10. }
      11. }

      Positive Reactions
      1. this work great, thanx...

All usage scenarios for API commons-httpclient
  • HTTP POST using JSON in Java

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. String postUrl="www.site.com"
    2. // put in your urlGson gson= new Gson()
    3. HttpPost post = new HttpPost(postUrl)
    4. StringEntity postingString =new StringEntity(gson.toJson(pojo1))
    5. //convert your pojo to jsonpost.setEntity(postingString)
    6. post.setHeader("Content-type", "application/json")
    7. HttpResponse response = httpClient.execute(post)

  • How to send a String array as basic name value pair as HTTPPOST?

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. for (int i = 0
    2. i < type.length
    3. i++) { nameValuePairs.add(new BasicNameValuePair("type[]",type[i]))
    4. }

  • Retrieve Data by passing a parameter to url in Android

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpGet get = new HttpGet(url)

  • When using JSON in Fragments the app is not responding in Android Development

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpResponse httpResponse = httpClient.execute(httpPost)

  • When using JSON in Fragments the app is not responding in Android Development

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. class TheTask extends AsyncTask<String, String, String> {
    2. @override
    3. protected String doInbackground(String... params) {
    4. String _response = null
    5. try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
    6. HttpPost httpPost = new HttpPost(params[0])
    7. HttpResponse httpResponse = httpClient.execute(httpPost)
    8. HttpEntity httpEntity = httpResponse.getEntity()
    9. _response = EntityUtils.toString(httpEntity)
    10. } catch (Exception e) {
    11. e.printStacktrace()
    12. }
    13. return _response
    14. }
    15. @Override
    16. protected void onPostExecute(
    17. String result) { // TODO Auto-generated method stub super.onPostExecute(result)
    18. Log.i(".......", result)
    19. }
    20. }

  • How to send a Json to a web service using HttpPost

    now try to understand the process how it works. Send string entity instead CODE This code will send json as string entity to server and receives HttpEntity as response . details

    Reactions - Positive 0, Negative 3, Others 0

    1. HttpClient client = new DefaultHttpClient()
    2. HttpUriRequest request
    3. request = new HttpPost(<-URL->)
    4. StringEntity entity = new StringEntity(<-Your JSON string->)
    5. ((HttpPost) request).setEntity(entity)
    6. ((HttpPost) request).setHeader("Content-Type", "application/json")
    7. HttpResponse response = client.execute(request)
    8. HttpEntity entity = response.getEntity()

    Negative Reactions
    1. keep giving me the same error :(.
    2. i dont know what a stacktrace is, i feel really bad.
    3. Hi , i get an error in HttpResponse response client.execute(request); the error is a null pointer exception.
    Other Reactions
    1. ?
    2. can u send ur stacktrace??
    3. try using above code.
    4. tell me at which line are you getting a null pointer exception?

  • Parsing Twitter API 1.1 JSON

    You forgot to close the ProgressDialog in onPostExecute method.just do this in onPostExecute like this. . details

    Reactions - Positive 7, Negative 4, Others 0

    1. @Overrideprotected void onPostExecute(Integer result) { pd.dismiss()
    2. // Extract Token from JSON stream try { JSONObject root = new JSONObject(jsonTokenStream)
    3. twitterToken = root.getString("access_token")
    4. } catch (Exception e) { Log.e("loadTwitterToken", "onPost Error:" + e.getMessage())
    5. } twitterText.setText("Got Token!")
    6. // Now that we have a oAuth Token, lets get our JSON feed from twitter. // We call it from here to make sure the Token has been received already. new loadTwitterFeed().execute()
    7. }

    Positive Reactions
    1. I've made strides in the code.
    2. +1 save my lots of search and time..
    3. Thanks for that @Priyanka.
    4. So it has authorized properly, but stops there.
    5. I appreciate your help so far.
    6. Thanks for the explanation @Priyanka!
    7. The only problem I'm having now is getting the R.java file to create an android.R.id.list, but my ListView id seems fine: "android:id="@android:id/list" Could anything else be causing it not to generate?
    Negative Reactions
    1. Again, it still doesn't crash or show errors, but I get as far as the status telling me "Got Token!"
    2. It should be the last blocks in the file.
    3. @reekdev when R.java file is not created than probably the error is in res folder.Check all .xml files if any error is there , also check your imports packages is there any package name 'android.R' remove it and if you use 'android:id="@android:id/list' means implicit android list than you should extends your class with ListActivity.
    4. I've found that I needed to change the XML TextView to ListView and drop the ScrollView.
    Other Reactions
    1. Can you tell if I set up the parse properly to output a list of tweets from my updated java?
    2. I can tell I'm close.
    3. I've made a few updates to the code.

  • HTTP POST using JSON in Java

    momo's answer for Apache HttpClient version 4.3.1 or later. I'm using JSON Java to build my JSON object . details

    Reactions - Positive 0, Negative 0, Others 0

    1. JSONObject json = new JSONObject()
    2. json.put("someKey", "someValue")
    3. CloseableHttpClient httpClient = HttpClientBuilder.create().build()
    4. try { HttpPost request = new HttpPost("http://yoururl")
    5. StringEntity params = new StringEntity(json.toString())
    6. request.addHeader("content-type", "application/x-www-form-urlencoded")
    7. request.setEntity(params)
    8. httpClient.execute(request)
    9. // handle response here...} catch (Exception ex) { // handle exception here} finally { httpClient.close()
    10. }

  • How to make a "raw" string out of JSON in Java

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. public static JSONArray getJSONArrayFromURL(String url) { // initialize InputStream is = null
    2. String result = ""
    3. JSONArray jArray = null
    4. Log.d("URL_SEARCH", url)
    5. // http post try { HttpClient httpclient = new DefaultHttpClient()
    6. HttpPost httppost = new HttpPost(url)
    7. HttpResponse response = httpclient.execute(httppost)
    8. HttpEntity entity = response.getEntity()
    9. is = entity.getContent()
    10. } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString())
    11. } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8)
    12. StringBuilder sb = new StringBuilder()
    13. String line = null
    14. while ((line = reader.readLine()) != null) { sb.append(line + "\n")
    15. } is.close()
    16. result = sb.toString()
    17. } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString())
    18. } // try parse the string to a JSON object try { jArray = new JSONArray(result)
    19. Log.d("URL_SEARCH", "JSON: " + jArray.length())
    20. } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString())
    21. } return jArray
    22. }

  • How to fetch data of API through JSONArray

    TharakaNirmana-Please help me for fetching path of image its urgent work for me. Step 1 copy the WEBSERVICE URL and paste in to your browser this will hit the web service and will show you the response use chrome will be more helpful to see the JSON response Step 2 analyse the structure of your JSON responsefirst of all you will be reading the complete response as a String create a JSON OBJECT from the String now convert that JSON object into a JSONARRAY object now that you have a JSONARRAY iterate the JSON Array and store one by one Object inside the iteration loop for JSON array for each JSON OBJECT call the value by their namesee in JSON you have key value pairs you can call JSONOBJECT.getString("variable name which retrieves String or you can get other datatypes like this also try this on your own post me the status will be responding you with modified code afterwards I tried to resolve it for you here is the class see the first method is the same as you wrote itin the second method i am trying to traverse the JSON response step by step.see you have to be careful about your JSON response 1 your complete response is a JSON OBJECT 2 if any element is written like this is a JSON Object 3 if any element is writen like this is value inside you json object which you can get by 4 if any element is writen like then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by and then you can traverse the elements of the JSON ARRAY by now you can traverse and retrieve the value you want post me if any help needed further . details

    Reactions - Positive 0, Negative 1, Others 0

    1. package com.hussain.StackOverFlow
    2. import java.io.BufferedReader
    3. import java.io.InputStream
    4. import java.io.InputStreamReader
    5. import java.net.URI
    6. import java.util.ArrayList
    7. import org.apache.http.HttpResponse
    8. import org.apache.http.client.HttpClient
    9. import org.apache.http.client.methods.HttpGet
    10. import org.apache.http.impl.client.DefaultHttpClient
    11. import org.apache.http.params.HttpConnectionParams
    12. import org.apache.http.params.HttpParams
    13. import org.json.JSONArray
    14. import org.json.JSONException
    15. import org.json.JSONObject
    16. public class FarhaSameer1 { public static void main(String[] args) { String asd = FarhaSameer1.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb")
    17. FarhaSameer1.parseFromJSONResponse(asd)
    18. } // API link // http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb // String Method to fetech data from server public static String sendRequest(String url) { String result = ""
    19. try { HttpClient client = new DefaultHttpClient()
    20. HttpParams httpParameters = client.getParams()
    21. HttpConnectionParams.setConnectionTimeout(httpParameters, 5000)
    22. HttpConnectionParams.setSoTimeout(httpParameters, 5000)
    23. HttpConnectionParams.setTcpNoDelay(httpParameters, true)
    24. HttpGet request = new HttpGet()
    25. request.setURI(new URI(url))
    26. HttpResponse response = client.execute(request)
    27. InputStream ips = response.getEntity().getContent()
    28. BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"))
    29. StringBuilder sb = new StringBuilder()
    30. String s
    31. while (true) { s = buf.readLine()
    32. if (s == null || s.length() == 0) break
    33. sb.append(s)
    34. } buf.close()
    35. ips.close()
    36. result = sb.toString()
    37. } catch (Exception e) { e.printStackTrace()
    38. } return result
    39. } public static void parseFromJSONResponse(String respo) { JSONObject myjson
    40. try { myjson = new JSONObject(respo)
    41. JSONObject jsonObj1 = myjson.getJSONObject("feed")
    42. JSONArray jsonObj2 = jsonObj1.getJSONArray("entry")
    43. JSONObject jsonObj3 = jsonObj2.getJSONObject(0)
    44. System.out.println(jsonObj3.getJSONObject("content"))
    45. System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString())
    46. } catch (JSONException e) { e.printStackTrace()
    47. } } }

    Negative Reactions
    1. a little help is here , URL_http://stackoverflow.com/questions/16544388 /converting-jsonarray-string-to-array/16544515#16544515.
    Other Reactions
    1. ?
    2. @FarhaSameer : was it enough ?

  • get JSON object from a HTTP response

    If you are supposed to get a JSON Object you can just put . Do this to get the JSON More details here from-httpresponse get-json-from-HttpResponse . details

    Reactions - Positive 0, Negative 0, Others 0

    1. String json = EntityUtils.toString(response.getEntity())

  • How to handle HTTP timeout?

    Corrected it to catch both. Increase your time of waiting for response like . details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 )
    2. //1 minuteHttpConnectionParams.setSoTimeout( httpParameters, 90000 )
    3. // 1.5 minute

  • Java: Gson and encoding

    The webserver could decode correctly those characters. By configuring the HttpClient for UTF encoding the problem disappeared here is my working code . details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpParams httpParams = new BasicHttpParams()
    2. HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8)
    3. HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8)
    4. HttpClient client = new DefaultHttpClient(httpParams)
    5. HttpPost request = new HttpPost(serverURL)
    6. StringEntity str = null
    7. String jsonString = gson.toJson(yourdata)
    8. str = new StringEntity(jsonString, HTTP.UTF_8)
    9. request.setEntity(str)
    10. request.setHeader("Accept", "application/json")
    11. request.setHeader("Content-type", "application/json")
    12. client.execute(request)

  • simplest way to read json from a URL in java

    construct a JSON object with this string more at json.org . hi friends i done the json parser in simplest way here it is this class returns the json object from the url and when you want the json object you just call this class and the method in it your activity class my code is here here the json key is denoted that the key in your json file this is a simple json file example json":"hi" here json is key and hi is value this will get your json value to string contentthank you . details

    Reactions - Positive 0, Negative 0, Others 0

    1. package com.inzane.shoapp.activity
    2. import java.io.BufferedReader
    3. import java.io.IOException
    4. import java.io.InputStream
    5. import java.io.InputStreamReader
    6. import java.io.UnsupportedEncodingException
    7. import org.apache.http.HttpEntity
    8. import org.apache.http.HttpResponse
    9. import org.apache.http.client.ClientProtocolException
    10. import org.apache.http.client.methods.HttpPost
    11. import org.apache.http.impl.client.DefaultHttpClient
    12. import org.json.JSONException
    13. import org.json.JSONObject
    14. import android.util.Log
    15. public class JSONParser {static InputStream is = null
    16. static JSONObject jObj = null
    17. static String json = ""
    18. // constructorpublic JSONParser() {}public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
    19. HttpPost httpPost = new HttpPost(url)
    20. HttpResponse httpResponse = httpClient.execute(httpPost)
    21. HttpEntity httpEntity = httpResponse.getEntity()
    22. is = httpEntity.getContent()
    23. } catch (UnsupportedEncodingException e) { e.printStackTrace()
    24. } catch (ClientProtocolException e) { e.printStackTrace()
    25. } catch (IOException e) { e.printStackTrace()
    26. } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8)
    27. StringBuilder sb = new StringBuilder()
    28. String line = null
    29. while ((line = reader.readLine()) != null) { sb.append(line + "\n")
    30. System.out.println(line)
    31. } is.close()
    32. json = sb.toString()
    33. } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString())
    34. } // try parse the string to a JSON object try { jObj = new JSONObject(json)
    35. } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString())
    36. System.out.println("error on parse data in jsonparser.java")
    37. } // return JSON String return jObj
    38. }}

  • JSONArray cannot be converted to JSONObject given a string

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. ... public JSONObject getJSONfromURL (String url){ //HTTP call try{ URLConnection connection = new URL(url).openConnection()
    2. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16)
    3. StringBuffer builder = new StringBuffer()
    4. String line
    5. while ((line = reader.readLine()) != null) { builder.append(line).append("\n")
    6. } String blah = builder.toString()
    7. //Parsing string into JSONArray JSONArray data = new JSONArray(new String(blah))
    8. for(int i=0
    9. i < data.length()
    10. i++) { object = data.getJSONObject(i)
    11. String id = object.getString("id")
    12. String value = object.getString("name")
    13. Log.d("Item name: ", value)
    14. } } catch(Exception e){ Log.e("Http Error","Error in http connection " + e.toString())
    15. } return object
    16. }..

  • Error with JSON data Android Illegal Argument HttpClient

    In this you can also pass your required parameters. . details

    Reactions - Positive 1, Negative 0, Others 0

    1. import java.io.BufferedReader
    2. import java.io.IOException
    3. import java.io.InputStream
    4. import java.io.InputStreamReader
    5. import java.net.URLEncoder
    6. import java.util.ArrayList
    7. import org.apache.http.HttpEntity
    8. import org.apache.http.HttpResponse
    9. import org.apache.http.NameValuePair
    10. import org.apache.http.client.ClientProtocolException
    11. import org.apache.http.client.HttpClient
    12. import org.apache.http.client.entity.UrlEncodedFormEntity
    13. import org.apache.http.client.methods.HttpGet
    14. import org.apache.http.client.methods.HttpPost
    15. import org.apache.http.client.methods.HttpUriRequest
    16. import org.apache.http.impl.client.DefaultHttpClient
    17. import org.apache.http.message.BasicNameValuePair
    18. import org.apache.http.protocol.HTTP
    19. import org.json.JSONException
    20. import org.json.JSONObject
    21. public class JsonClient { public enum RequestMethod{ GET, POST } private ArrayList <NameValuePair> params
    22. private ArrayList <NameValuePair> headers
    23. private String url
    24. private int responseCode
    25. private String message
    26. private JSONObject jsonResponse
    27. public JSONObject getResponse() { return jsonResponse
    28. } public String getErrorMessage() { return message
    29. } public int getResponseCode() { return responseCode
    30. } public JsonClient(String url) { this.url = url
    31. params = new ArrayList<NameValuePair>()
    32. headers = new ArrayList<NameValuePair>()
    33. } public void addParam(String name, String value) { params.add(new BasicNameValuePair(name, value))
    34. } public void addHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value))
    35. } public void execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""
    36. if(!params.isEmpty()){ combinedParams += "?"
    37. for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8")
    38. if(combinedParams.length() > 1) { combinedParams += "&" + paramString
    39. } else { combinedParams += paramString
    40. } } } HttpGet request = new HttpGet(url + combinedParams)
    41. //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
    42. } executeRequest(request, url)
    43. break
    44. } case POST: { HttpPost request = new HttpPost(url)
    45. //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
    46. } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8))
    47. } executeRequest(request, url)
    48. break
    49. } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient()
    50. HttpResponse httpResponse
    51. try { httpResponse = client.execute(request)
    52. responseCode = httpResponse.getStatusLine().getStatusCode()
    53. message = httpResponse.getStatusLine().getReasonPhrase()
    54. HttpEntity entity = httpResponse.getEntity()
    55. if (entity != null) { InputStream instream = entity.getContent()
    56. String response = convertStreamToString(instream)
    57. jsonResponse = new JSONObject(response)
    58. // Closing the input stream will trigger connection release instream.close()
    59. } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown()
    60. e.printStackTrace()
    61. } catch (IOException e) { client.getConnectionManager().shutdown()
    62. e.printStackTrace()
    63. }catch (JSONException e) { e.printStackTrace()
    64. } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is))
    65. StringBuilder sb = new StringBuilder()
    66. String line = null
    67. try { while ((line = reader.readLine()) != null) { sb.append(line + "\n")
    68. } } catch (IOException e) { e.printStackTrace()
    69. } finally { try { is.close()
    70. } catch (IOException e) { e.printStackTrace()
    71. } } return sb.toString()
    72. }}

    Positive Reactions
    1. Thanks for this.
    Other Reactions
    1. I'll be able to use this in the future for sure.

  • I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

    It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

    Reactions - Positive 5, Negative 0, Others 0

    1. import org.apache.http.HttpResponse
    2. import org.apache.http.client.HttpClient
    3. import org.apache.http.client.methods.HttpPut
    4. import org.apache.http.entity.StringEntity
    5. import org.apache.http.impl.client.DefaultHttpClient
    6. import net.sf.json.JSONArray
    7. import net.sf.json.JSONObject
    8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
    9. for (int i = 0
    10. i < 5
    11. i++) { JSONObject jsonAddressObj = new JSONObject()
    12. jsonAddressObj.put("address1", "a")
    13. jsonAddressObj.put("address2", "b")
    14. jsonAddressObj.put("city", "c")
    15. jsonAddressObj.put("state", "d")
    16. jsonAddressObj.put("postalCode", "e")
    17. jsonAddressArray.add(jsonAddressObj)
    18. } System.out.println(jsonAddressArray)
    19. HttpClient httpClient = new DefaultHttpClient()
    20. try { HttpPut request = new HttpPut("http://yourAddressHere")
    21. StringEntity params =new StringEntity(jsonAddressArray.toString())
    22. request.setEntity(params)
    23. HttpResponse response = httpClient.execute(request)
    24. System.out.println(response.toString())
    25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
    26. }}

    Positive Reactions
    1. Thanks, and it's good your pointing that out.
    2. But +1 for everything else!.
    3. I just put the values to my jsonAddressObj.
    4. I do not want to send harcoded values to any of the fields.
    5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
    Other Reactions
    1. OK.
    2. I need to send the following as http request.
    3. Yeh, I got the feeling we're not using the same library.
    4. I did take out the for loop.
    5. That helped me.
    6. I want the address to be fetched from the EditText.
    7. That is the reason i used txtAddress1.getText().toString().
    8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
    9. Have you read anything about these technologies or checked the documentation?
    10. That did that work for me.
    11. Are you referring to a post or a put ?
    12. Is it just me or you're never adding anything to your jsonAddressArray ?
    13. Passed the jsonAddressObj to jsonObjSend.
    14. Http request is quite broad.
    15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
    16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
    17. Here is what I want to do.
    18. it is a put method.
    19. Yeh your right...it's from the original code.

  • Passing String array to PHP as POST

    I'll give that a try now thanks . To pass an array to php in query string you should add to identifier and add every item as separate entry so something like this should work now POST['devices' on php side will contain an array. details

    Reactions - Positive 0, Negative 1, Others 0

    1. nameValuePairs.add(new BasicNameValuePair("devices[]", device1))
    2. nameValuePairs.add(new BasicNameValuePair("devices[]", device2))
    3. nameValuePairs.add(new BasicNameValuePair("devices[]", device3))

    Negative Reactions
    1. Hey, I am trying this but it isn't working, I don't know how to get Java to print out PHP errors so I am just getting an "Error executing script" message.
    Other Reactions
    1. I have updated my post with the code I am trying..

  • Android JSON api trouble with PUT operations

    First important)** you need to determine if your request was successful prior to processing the response body. Given the structure of your code I would recommend declaring a status code variable at the beginning of your retrieval method and setting it after each execute Second important)** you need to check that your response entity is non null before calling any methods on it. details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpResponse httpResponse = httpClient.execute(httpPut)
    2. status = httpResponse.getStatusLine().getStatusCode()

  • Get jSON Response for POST

    If you have the Log please paste it in your question and also please update your question with the new code. Here what you need to do . details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpResponse mHttpResponse = mHttpClient.execute(httppost)
    2. StatusLine status = mHttpResponse.getStatusLine()
    3. int response = status.getStatusCode()

  • Get jSON Response for POST

    Hop it will help you. This is what you need . details

    Reactions - Positive 2, Negative 0, Others 0

    1. String jsonString = EntityUtils.toString(response.getEntity())

    Positive Reactions
    1. I have tried implementing you code ANR !!!
    2. If you have the Log please paste it in your question and also please update your question with the new code.
    Other Reactions
    1. !.
    2. You must implement the Http code in AsyncTask because it is network code.

  • A field of type "String" does not appear in the result (json) serialization of the vraptor controller

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. result.use(Results.json()).indented().from(list) .include("codigoComposto").serialize()

  • Accessing JSON in using JSESSION ID or Authentication

    In HttpClient 3 this looks like this How to set the cookie in HttpClient 4 can be found here do-i-set-cookie-with-sessionid-for-post-request Apache-HttpClient-4.0.3 how-do-I-set-cookie-with-sessionID-for-POST-request Or you can take it a little bit lower level and add the full header. . details

    Reactions - Positive 4, Negative 1, Others 0

    1. HttpGet httpget = new HttpGet(url)
    2. httpget.addHeader("Cookie", "JSESSIONID=...")

    Positive Reactions
    1. For HttpClient 4 manually setting the cookie looks like this URL_http://stackoverflow.com/questions/4166129/apache-httpclient-4-0-3-how-do-i -set-cookie-with-sessionid-for-post-request.
    2. Thanks so much.
    3. So I can do something like method.setRequestHeader("Cookie", "JSESSIONID=F7B89109EABD2FFD58A0096AF2123199"); and it should work?
    4. Thanks.
    Negative Reactions
    1. I used Selenium to "login" then capture the JSESSION ID and pass that into my httpget.addHeader("Cookie", "JSESSIONID=" + jsessionIdVal);.
    Other Reactions
    1. This allowed me to get past the login screen.
    2. Ach, I see now that you ask for HttpClient 4.
    3. And how can I use HttpMethod and GetMethod?
    4. Not that it makes that much of a difference.
    5. The names I used are for HttpClient 3.
    6. I've seen this before but couldn't figure out what postData was in the question and answers.
    7. I already added the JAR files that I downloaded from Apache website you linked to but now sure what import to call.
    8. I've added it to the answer.

  • Connect to a MySQL database from android. No indication it's working/not working...?

    Take a look on this link greater-in-android HTTP-Client-API-level-11-or-greater-in-Android . Also for the POST request I think that you can use this code . details

    Reactions - Positive 4, Negative 0, Others 0

    1. public String post(String str) { String result = ""
    2. try { HttpParams httpParameters = new BasicHttpParams()
    3. int timeoutConnection = 3000
    4. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection)
    5. int timeoutSocket = 5000
    6. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket)
    7. DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters)
    8. HttpPost postRequest = new HttpPost(SERVER_ADDRESS)
    9. StringEntity input = new StringEntity(str)
    10. input.setContentType("application/json")
    11. postRequest.setEntity(input)
    12. HttpResponse response = httpClient.execute(postRequest)
    13. result = getResult(response).toString()
    14. httpClient.getConnectionManager().shutdown()
    15. } catch (Exception e) { System.out.println(e.getMessage())
    16. } return result
    17. }private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException { StringBuilder result = new StringBuilder()
    18. BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024)
    19. String output
    20. while ((output = br.readLine()) != null) result.append(output)
    21. return result
    22. }

    Positive Reactions
    1. Thanks, didn't think about having this going in the background via threads.
    2. You are welcome.
    3. Thanks for the code too.
    4. hope that it is helpful for you.
    Other Reactions
    1. That will have to be implemented.

  • how can a create a thread for a connection json call for android

    You shouldn't perform network operations in UI thread!For instance you can create AsyncTask in your class. It may looks similar to this After that simply call in onCreate method to start AsyncTask. details

    Reactions - Positive 1, Negative 0, Others 0

    1. private class ParseTask extends AsyncTask<Params, Progress, Result> {
    2. @Override
    3. protected Result doInBackground(Params params) { // get url Params url = params[0]
    4. // create HttpClient etc. ... // get response, and parse json // return return result
    5. }
    6. @Override
    7. protected void onPostExecute(
    8. Result
    9. result) { // now when you have result from parsed json, // update application UI or whatever you need someEditText.setText(value_from_result)
    10. }
    11. }

    Positive Reactions
    1. this work great, thanx...

  • Empty exception when converting inputstream to JSONArrary

    Completely reinstalled my system including Windows 7) but still the same issue. I would first recommend that you change out all your stream monitoring code for the parser in the framework so the response block would become This might help guarantee you get all the correct data down from the server and properly formatted. details

    Reactions - Positive 1, Negative 1, Others 0

    1. HttpResponse response = httpClient.execute(request)
    2. String tekst = EntityUtils.toString( response.getEntity() )

    Positive Reactions
    1. Thanks for your response.
    Negative Reactions
    1. Unfortunately this gives the same JSONException.

  • HttpPost response doesn't return the json object

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpResponse httpResponse = httpClient.execute(httpPost)
    2. if (httpResponse != null) { String resp = httpResponse.toString()

  • How can I read MYSQL Database from Android?

    Thank you again!. This should work . details

    Reactions - Positive 0, Negative 0, Others 0

    1. package com.Online.Test
    2. import java.io.IOException
    3. import org.apache.http.HttpEntity
    4. import org.apache.http.HttpResponse
    5. import org.apache.http.client.ClientProtocolException
    6. import org.apache.http.client.HttpClient
    7. import org.apache.http.client.methods.HttpPost
    8. import org.apache.http.impl.client.DefaultHttpClient
    9. import org.apache.http.util.EntityUtils
    10. import org.json.JSONArray
    11. import org.json.JSONException
    12. import org.json.JSONObject
    13. import android.app.Activity
    14. import android.os.AsyncTask
    15. import android.os.Bundle
    16. import android.widget.TextView
    17. import android.widget.Toast
    18. public class OnlineTestActivity extends Activity { /** Called when the activity is first created. */ TextView resultView
    19. HttpClient client
    20. JSONObject json
    21. String Dat
    22. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
    23. setContentView(R.layout.main)
    24. resultView = (TextView) findViewById(R.id.tvjson)
    25. client = new DefaultHttpClient()
    26. try { json = RedData()
    27. } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
    28. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
    29. } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
    30. } Dat = json.toString()
    31. new Read().onPostExecute(Dat)
    32. } public JSONObject RedData() throws ClientProtocolException, IOException, JSONException { HttpPost httppost = new HttpPost("//link.php")
    33. HttpResponse r = client.execute(httppost)
    34. // int status = r.getStatusLine().getStatusCode()
    35. //if (status == 200) { HttpEntity e = r.getEntity()
    36. String data = EntityUtils.toString(e)
    37. JSONArray jArray = new JSONArray(data)
    38. JSONObject last = jArray.getJSONObject(0)
    39. // 0 -> the last object return last
    40. // } else { // Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG)
    41. // return null
    42. //} } public class Read extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { json = RedData()
    43. //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG)
    44. return json.getString(arg0[0])
    45. } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
    46. } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
    47. } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
    48. } return null
    49. } @Override protected void onPostExecute(String data) { // TODO Auto-generated method stub resultView.setText(data)
    50. } }}

    Other Reactions
    1. It would be even better if you explained the code and/or corrections.

  • process in-app apple receipt with java

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES)

  • JSON Object returns a null pointer

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. EntityUtils.toString(entity)

  • HTTP POST using JSON in Java

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. HttpClient httpClient = new DefaultHttpClient()
    2. try { HttpPost request = new HttpPost("http://yoururl")
    3. StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ")
    4. request.addHeader("content-type", "application/x-www-form-urlencoded")
    5. request.setEntity(params)
    6. HttpResponse response = httpClient.execute(request)
    7. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
    8. }

  • Using HttpClient and HttpPost in Android with post parameters

    Thanks for the help. I've just checked and i have the same code as you and it works perferctly.The only difference is how i fill my List for the params I use a ArrayList<BasicNameValuePair params and fill it this way I do not use any JSONObject to send params to the webservices. details

    Reactions - Positive 1, Negative 0, Others 0

    1. params.add(new BasicNameValuePair("apikey", apikey)

    Positive Reactions
    1. Since I'm working in parallell with an Iphone developer, and his app actually posts data, I have no other choice than also submitting data as JSON.
    Other Reactions
    1. I tried sending just the two valuepairs, but no difference.

  • Android - Connecting to MySQL database

    Insert following line below TextView txt Below rootLayout.addView(txt) insert following two lines Now modify this line nameValuePairs.add(new BasicNameValuePair("name","tom")) to fetch value from the EditText. You can also create one for year. details

    Reactions - Positive 0, Negative 0, Others 0

    1. nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()))

  • ProgressDialog is never dismissed when fetching JSON with AsyncTask

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. String jsontext = EntityUtils.toString(response.getEntity())