Mined and Summarized Use Cases For API: commons-httpclient
-
HTTP POST using JSON in Java
None .. details
- String postUrl="www.site.com"
- // put in your urlGson gson= new Gson()
- HttpPost post = new HttpPost(postUrl)
- StringEntity postingString =new StringEntity(gson.toJson(pojo1))
- //convert your pojo to jsonpost.setEntity(postingString)
- post.setHeader("Content-type", "application/json")
- HttpResponse response = httpClient.execute(post)
-
How to send a String array as basic name value pair as HTTPPOST?
None .. details
- for (int i = 0
- i < type.length
- i++) { nameValuePairs.add(new BasicNameValuePair("type[]",type[i]))
- }
• See Also (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
- nameValuePairs.add(new BasicNameValuePair("devices[]", device1))
- nameValuePairs.add(new BasicNameValuePair("devices[]", device2))
- nameValuePairs.add(new BasicNameValuePair("devices[]", device3))
Negative Reactions
- 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
- I have updated my post with the code I am trying..
-
Retrieve Data by passing a parameter to url in Android
None .. details
- HttpGet get = new HttpGet(url)
• See Also (4)
-
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
- HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 )
- //1 minuteHttpConnectionParams.setSoTimeout( httpParameters, 90000 )
- // 1.5 minute
-
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
- HttpGet httpget = new HttpGet(url)
- httpget.addHeader("Cookie", "JSESSIONID=...")
Positive Reactions
- 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.
- Thanks so much.
- So I can do something like method.setRequestHeader("Cookie", "JSESSIONID=F7B89109EABD2FFD58A0096AF2123199"); and it should work?
- Thanks.
Negative Reactions
- I used Selenium to "login" then capture the JSESSION ID and pass that into my httpget.addHeader("Cookie", "JSESSIONID=" + jsessionIdVal);.
Other Reactions
- This allowed me to get past the login screen.
- Ach, I see now that you ask for HttpClient 4.
- And how can I use HttpMethod and GetMethod?
- Not that it makes that much of a difference.
- The names I used are for HttpClient 3.
- I've seen this before but couldn't figure out what postData was in the question and answers.
- I already added the JAR files that I downloaded from Apache website you linked to but now sure what import to call.
- I've added it to the answer.
-
HttpPost response doesn't return the json object
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpResponse httpResponse = httpClient.execute(httpPost)
- if (httpResponse != null) { String resp = httpResponse.toString()
-
JSON Object returns a null pointer
-
When using JSON in Fragments the app is not responding in Android Development
None .. details
- class TheTask extends AsyncTask<String, String, String> {
- @override
- protected String doInbackground(String... params) {
- String _response = null
- try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
- HttpPost httpPost = new HttpPost(params[0])
- HttpResponse httpResponse = httpClient.execute(httpPost)
- HttpEntity httpEntity = httpResponse.getEntity()
- _response = EntityUtils.toString(httpEntity)
- } catch (Exception e) {
- e.printStacktrace()
- }
- return _response
- }
- @Override
- protected void onPostExecute(
- String result) { // TODO Auto-generated method stub super.onPostExecute(result)
- Log.i(".......", result)
- }
- }
-
When using JSON in Fragments the app is not responding in Android Development
None .. details
- HttpResponse httpResponse = httpClient.execute(httpPost)
• See Also (4)
-
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
- String json = EntityUtils.toString(response.getEntity())
-
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
- result.use(Results.json()).indented().from(list) .include("codigoComposto").serialize()
-
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
- HttpResponse response = httpClient.execute(request)
- String tekst = EntityUtils.toString( response.getEntity() )
Positive Reactions
- Thanks for your response.
Negative Reactions
- Unfortunately this gives the same JSONException.
-
ProgressDialog is never dismissed when fetching JSON with AsyncTask
None details
Reactions - Positive 0, Negative 0, Others 0
- String jsontext = EntityUtils.toString(response.getEntity())
-
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
- HttpClient client = new DefaultHttpClient()
- HttpUriRequest request
- request = new HttpPost(<-URL->)
- StringEntity entity = new StringEntity(<-Your JSON string->)
- ((HttpPost) request).setEntity(entity)
- ((HttpPost) request).setHeader("Content-Type", "application/json")
- HttpResponse response = client.execute(request)
- HttpEntity entity = response.getEntity()
Negative Reactions
- keep giving me the same error :(.
- i dont know what a stacktrace is, i feel really bad.
- Hi , i get an error in HttpResponse response client.execute(request); the error is a null pointer exception.
Other Reactions
- ?
- can u send ur stacktrace??
- try using above code.
- tell me at which line are you getting a null pointer exception?
• See Also (5)
-
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
- JSONObject json = new JSONObject()
- json.put("someKey", "someValue")
- CloseableHttpClient httpClient = HttpClientBuilder.create().build()
- try { HttpPost request = new HttpPost("http://yoururl")
- StringEntity params = new StringEntity(json.toString())
- request.addHeader("content-type", "application/x-www-form-urlencoded")
- request.setEntity(params)
- httpClient.execute(request)
- // handle response here...} catch (Exception ex) { // handle exception here} finally { httpClient.close()
- }
-
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
- HttpParams httpParams = new BasicHttpParams()
- HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8)
- HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8)
- HttpClient client = new DefaultHttpClient(httpParams)
- HttpPost request = new HttpPost(serverURL)
- StringEntity str = null
- String jsonString = gson.toJson(yourdata)
- str = new StringEntity(jsonString, HTTP.UTF_8)
- request.setEntity(str)
- request.setHeader("Accept", "application/json")
- request.setHeader("Content-type", "application/json")
- client.execute(request)
-
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
- private class ParseTask extends AsyncTask<Params, Progress, Result> {
- @Override
- protected Result doInBackground(Params params) { // get url Params url = params[0]
- // create HttpClient etc. ... // get response, and parse json // return return result
- }
- @Override
- protected void onPostExecute(
- Result
- result) { // now when you have result from parsed json, // update application UI or whatever you need someEditText.setText(value_from_result)
- }
- }
Positive Reactions
- this work great, thanx...
-
How can I read MYSQL Database from Android?
Thank you again!. This should work . details
Reactions - Positive 0, Negative 0, Others 0
- package com.Online.Test
- import java.io.IOException
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.util.EntityUtils
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- import android.app.Activity
- import android.os.AsyncTask
- import android.os.Bundle
- import android.widget.TextView
- import android.widget.Toast
- public class OnlineTestActivity extends Activity { /** Called when the activity is first created. */ TextView resultView
- HttpClient client
- JSONObject json
- String Dat
- @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
- setContentView(R.layout.main)
- resultView = (TextView) findViewById(R.id.tvjson)
- client = new DefaultHttpClient()
- try { json = RedData()
- } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
- } Dat = json.toString()
- new Read().onPostExecute(Dat)
- } public JSONObject RedData() throws ClientProtocolException, IOException, JSONException { HttpPost httppost = new HttpPost("//link.php")
- HttpResponse r = client.execute(httppost)
- // int status = r.getStatusLine().getStatusCode()
- //if (status == 200) { HttpEntity e = r.getEntity()
- String data = EntityUtils.toString(e)
- JSONArray jArray = new JSONArray(data)
- JSONObject last = jArray.getJSONObject(0)
- // 0 -> the last object return last
- // } else { // Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG)
- // return null
- //} } public class Read extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { json = RedData()
- //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG)
- return json.getString(arg0[0])
- } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
- } return null
- } @Override protected void onPostExecute(String data) { // TODO Auto-generated method stub resultView.setText(data)
- } }}
Other Reactions
- It would be even better if you explained the code and/or corrections.
-
HTTP POST using JSON in Java
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpClient httpClient = new DefaultHttpClient()
- try { HttpPost request = new HttpPost("http://yoururl")
- StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ")
- request.addHeader("content-type", "application/x-www-form-urlencoded")
- request.setEntity(params)
- HttpResponse response = httpClient.execute(request)
- // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
- }
-
Parsing Twitter API 1.1 JSON
You forgot to close the ProgressDialog in onPostExecute method.just do this in onPostExecute like this. . .. details
- @Overrideprotected void onPostExecute(Integer result) { pd.dismiss()
- // Extract Token from JSON stream try { JSONObject root = new JSONObject(jsonTokenStream)
- twitterToken = root.getString("access_token")
- } catch (Exception e) { Log.e("loadTwitterToken", "onPost Error:" + e.getMessage())
- } twitterText.setText("Got Token!")
- // 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()
- }
Positive Reactions
- I've made strides in the code.
- +1 save my lots of search and time..
- Thanks for that @Priyanka.
- So it has authorized properly, but stops there.
- I appreciate your help so far.
- Thanks for the explanation @Priyanka!
- 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
- Again, it still doesn't crash or show errors, but I get as far as the status telling me "Got Token!"
- It should be the last blocks in the file.
- @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.
- I've found that I needed to change the XML TextView to ListView and drop the ScrollView.
Other Reactions
- Can you tell if I set up the parse properly to output a list of tweets from my updated java?
- I can tell I'm close.
- I've made a few updates to the code.
-
How to make a "raw" string out of JSON in Java
None .. details
- public static JSONArray getJSONArrayFromURL(String url) { // initialize InputStream is = null
- String result = ""
- JSONArray jArray = null
- Log.d("URL_SEARCH", url)
- // http post try { HttpClient httpclient = new DefaultHttpClient()
- HttpPost httppost = new HttpPost(url)
- HttpResponse response = httpclient.execute(httppost)
- HttpEntity entity = response.getEntity()
- is = entity.getContent()
- } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString())
- } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8)
- StringBuilder sb = new StringBuilder()
- String line = null
- while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- } is.close()
- result = sb.toString()
- } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString())
- } // try parse the string to a JSON object try { jArray = new JSONArray(result)
- Log.d("URL_SEARCH", "JSON: " + jArray.length())
- } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString())
- } return jArray
- }
-
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
- package com.hussain.StackOverFlow
- import java.io.BufferedReader
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.net.URI
- import java.util.ArrayList
- import org.apache.http.HttpResponse
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpGet
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.params.HttpConnectionParams
- import org.apache.http.params.HttpParams
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- 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")
- FarhaSameer1.parseFromJSONResponse(asd)
- } // 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 = ""
- try { HttpClient client = new DefaultHttpClient()
- HttpParams httpParameters = client.getParams()
- HttpConnectionParams.setConnectionTimeout(httpParameters, 5000)
- HttpConnectionParams.setSoTimeout(httpParameters, 5000)
- HttpConnectionParams.setTcpNoDelay(httpParameters, true)
- HttpGet request = new HttpGet()
- request.setURI(new URI(url))
- HttpResponse response = client.execute(request)
- InputStream ips = response.getEntity().getContent()
- BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"))
- StringBuilder sb = new StringBuilder()
- String s
- while (true) { s = buf.readLine()
- if (s == null || s.length() == 0) break
- sb.append(s)
- } buf.close()
- ips.close()
- result = sb.toString()
- } catch (Exception e) { e.printStackTrace()
- } return result
- } public static void parseFromJSONResponse(String respo) { JSONObject myjson
- try { myjson = new JSONObject(respo)
- JSONObject jsonObj1 = myjson.getJSONObject("feed")
- JSONArray jsonObj2 = jsonObj1.getJSONArray("entry")
- JSONObject jsonObj3 = jsonObj2.getJSONObject(0)
- System.out.println(jsonObj3.getJSONObject("content"))
- System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString())
- } catch (JSONException e) { e.printStackTrace()
- } } }
Negative Reactions
- a little help is here , URL_http://stackoverflow.com/questions/16544388 /converting-jsonarray-string-to-array/16544515#16544515.
Other Reactions
- ?
- @FarhaSameer : was it enough ?
• See Also (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
- import java.io.BufferedReader
- import java.io.IOException
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.net.URLEncoder
- import java.util.ArrayList
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.NameValuePair
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.HttpClient
- import org.apache.http.client.entity.UrlEncodedFormEntity
- import org.apache.http.client.methods.HttpGet
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.client.methods.HttpUriRequest
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.message.BasicNameValuePair
- import org.apache.http.protocol.HTTP
- import org.json.JSONException
- import org.json.JSONObject
- public class JsonClient { public enum RequestMethod{ GET, POST } private ArrayList <NameValuePair> params
- private ArrayList <NameValuePair> headers
- private String url
- private int responseCode
- private String message
- private JSONObject jsonResponse
- public JSONObject getResponse() { return jsonResponse
- } public String getErrorMessage() { return message
- } public int getResponseCode() { return responseCode
- } public JsonClient(String url) { this.url = url
- params = new ArrayList<NameValuePair>()
- headers = new ArrayList<NameValuePair>()
- } public void addParam(String name, String value) { params.add(new BasicNameValuePair(name, value))
- } public void addHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value))
- } public void execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""
- if(!params.isEmpty()){ combinedParams += "?"
- for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8")
- if(combinedParams.length() > 1) { combinedParams += "&" + paramString
- } else { combinedParams += paramString
- } } } HttpGet request = new HttpGet(url + combinedParams)
- //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
- } executeRequest(request, url)
- break
- } case POST: { HttpPost request = new HttpPost(url)
- //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
- } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8))
- } executeRequest(request, url)
- break
- } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient()
- HttpResponse httpResponse
- try { httpResponse = client.execute(request)
- responseCode = httpResponse.getStatusLine().getStatusCode()
- message = httpResponse.getStatusLine().getReasonPhrase()
- HttpEntity entity = httpResponse.getEntity()
- if (entity != null) { InputStream instream = entity.getContent()
- String response = convertStreamToString(instream)
- jsonResponse = new JSONObject(response)
- // Closing the input stream will trigger connection release instream.close()
- } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown()
- e.printStackTrace()
- } catch (IOException e) { client.getConnectionManager().shutdown()
- e.printStackTrace()
- }catch (JSONException e) { e.printStackTrace()
- } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is))
- StringBuilder sb = new StringBuilder()
- String line = null
- try { while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- } } catch (IOException e) { e.printStackTrace()
- } finally { try { is.close()
- } catch (IOException e) { e.printStackTrace()
- } } return sb.toString()
- }}
Positive Reactions
- Thanks for this.
Other Reactions
- I'll be able to use this in the future for sure.
-
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
- package com.inzane.shoapp.activity
- import java.io.BufferedReader
- import java.io.IOException
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.io.UnsupportedEncodingException
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.impl.client.DefaultHttpClient
- import org.json.JSONException
- import org.json.JSONObject
- import android.util.Log
- public class JSONParser {static InputStream is = null
- static JSONObject jObj = null
- static String json = ""
- // constructorpublic JSONParser() {}public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
- HttpPost httpPost = new HttpPost(url)
- HttpResponse httpResponse = httpClient.execute(httpPost)
- HttpEntity httpEntity = httpResponse.getEntity()
- is = httpEntity.getContent()
- } catch (UnsupportedEncodingException e) { e.printStackTrace()
- } catch (ClientProtocolException e) { e.printStackTrace()
- } catch (IOException e) { e.printStackTrace()
- } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8)
- StringBuilder sb = new StringBuilder()
- String line = null
- while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- System.out.println(line)
- } is.close()
- json = sb.toString()
- } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString())
- } // try parse the string to a JSON object try { jObj = new JSONObject(json)
- } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString())
- System.out.println("error on parse data in jsonparser.java")
- } // return JSON String return jObj
- }}
-
JSONArray cannot be converted to JSONObject given a string
None .. details
- ... public JSONObject getJSONfromURL (String url){ //HTTP call try{ URLConnection connection = new URL(url).openConnection()
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16)
- StringBuffer builder = new StringBuffer()
- String line
- while ((line = reader.readLine()) != null) { builder.append(line).append("\n")
- } String blah = builder.toString()
- //Parsing string into JSONArray JSONArray data = new JSONArray(new String(blah))
- for(int i=0
- i < data.length()
- i++) { object = data.getJSONObject(i)
- String id = object.getString("id")
- String value = object.getString("name")
- Log.d("Item name: ", value)
- } } catch(Exception e){ Log.e("Http Error","Error in http connection " + e.toString())
- } return object
- }..
-
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
- import org.apache.http.HttpResponse
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpPut
- import org.apache.http.entity.StringEntity
- import org.apache.http.impl.client.DefaultHttpClient
- import net.sf.json.JSONArray
- import net.sf.json.JSONObject
- public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
- for (int i = 0
- i < 5
- i++) { JSONObject jsonAddressObj = new JSONObject()
- jsonAddressObj.put("address1", "a")
- jsonAddressObj.put("address2", "b")
- jsonAddressObj.put("city", "c")
- jsonAddressObj.put("state", "d")
- jsonAddressObj.put("postalCode", "e")
- jsonAddressArray.add(jsonAddressObj)
- } System.out.println(jsonAddressArray)
- HttpClient httpClient = new DefaultHttpClient()
- try { HttpPut request = new HttpPut("http://yourAddressHere")
- StringEntity params =new StringEntity(jsonAddressArray.toString())
- request.setEntity(params)
- HttpResponse response = httpClient.execute(request)
- System.out.println(response.toString())
- // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
- }}
Positive Reactions
- Thanks, and it's good your pointing that out.
- But +1 for everything else!.
- I just put the values to my jsonAddressObj.
- I do not want to send harcoded values to any of the fields.
- "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
- OK.
- I need to send the following as http request.
- Yeh, I got the feeling we're not using the same library.
- I did take out the for loop.
- That helped me.
- I want the address to be fetched from the EditText.
- That is the reason i used txtAddress1.getText().toString().
- And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
- Have you read anything about these technologies or checked the documentation?
- That did that work for me.
- Are you referring to a post or a put ?
- Is it just me or you're never adding anything to your jsonAddressArray ?
- Passed the jsonAddressObj to jsonObjSend.
- Http request is quite broad.
- 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.
- 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.
- Here is what I want to do.
- it is a put method.
- Yeh your right...it's from the original code.
-
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
- HttpResponse httpResponse = httpClient.execute(httpPut)
- status = httpResponse.getStatusLine().getStatusCode()
• See Also (1)
-
process in-app apple receipt with java
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES)
-
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
- HttpResponse mHttpResponse = mHttpClient.execute(httppost)
- StatusLine status = mHttpResponse.getStatusLine()
- int response = status.getStatusCode()
• See Also (2)
-
Get jSON Response for POST
Hop it will help you. This is what you need . details
Reactions - Positive 2, Negative 0, Others 0
- String jsonString = EntityUtils.toString(response.getEntity())
Positive Reactions
- I have tried implementing you code ANR !!!
- If you have the Log please paste it in your question and also please update your question with the new code.
Other Reactions
- !.
- You must implement the Http code in AsyncTask because it is network code.
-
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
- params.add(new BasicNameValuePair("apikey", apikey)
Positive Reactions
- 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
- I tried sending just the two valuepairs, but no difference.
-
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
- public String post(String str) { String result = ""
- try { HttpParams httpParameters = new BasicHttpParams()
- int timeoutConnection = 3000
- HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection)
- int timeoutSocket = 5000
- HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket)
- DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters)
- HttpPost postRequest = new HttpPost(SERVER_ADDRESS)
- StringEntity input = new StringEntity(str)
- input.setContentType("application/json")
- postRequest.setEntity(input)
- HttpResponse response = httpClient.execute(postRequest)
- result = getResult(response).toString()
- httpClient.getConnectionManager().shutdown()
- } catch (Exception e) { System.out.println(e.getMessage())
- } return result
- }private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException { StringBuilder result = new StringBuilder()
- BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024)
- String output
- while ((output = br.readLine()) != null) result.append(output)
- return result
- }
Positive Reactions
- Thanks, didn't think about having this going in the background via threads.
- You are welcome.
- Thanks for the code too.
- hope that it is helpful for you.
Other Reactions
- That will have to be implemented.
• See Also (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
- nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()))
-
cookiepolicy
-
process in-app apple receipt with java
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES)
-
-
httpclient
-
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
- HttpClient client = new DefaultHttpClient()
- HttpUriRequest request
- request = new HttpPost(<-URL->)
- StringEntity entity = new StringEntity(<-Your JSON string->)
- ((HttpPost) request).setEntity(entity)
- ((HttpPost) request).setHeader("Content-Type", "application/json")
- HttpResponse response = client.execute(request)
- HttpEntity entity = response.getEntity()
Negative Reactions
- keep giving me the same error :(.
- i dont know what a stacktrace is, i feel really bad.
- Hi , i get an error in HttpResponse response client.execute(request); the error is a null pointer exception.
Other Reactions
- ?
- can u send ur stacktrace??
- try using above code.
- tell me at which line are you getting a null pointer exception?
-
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
- HttpParams httpParams = new BasicHttpParams()
- HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8)
- HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8)
- HttpClient client = new DefaultHttpClient(httpParams)
- HttpPost request = new HttpPost(serverURL)
- StringEntity str = null
- String jsonString = gson.toJson(yourdata)
- str = new StringEntity(jsonString, HTTP.UTF_8)
- request.setEntity(str)
- request.setHeader("Accept", "application/json")
- request.setHeader("Content-type", "application/json")
- client.execute(request)
-
How to make a "raw" string out of JSON in Java
None details
Reactions - Positive 0, Negative 0, Others 0
- public static JSONArray getJSONArrayFromURL(String url) { // initialize InputStream is = null
- String result = ""
- JSONArray jArray = null
- Log.d("URL_SEARCH", url)
- // http post try { HttpClient httpclient = new DefaultHttpClient()
- HttpPost httppost = new HttpPost(url)
- HttpResponse response = httpclient.execute(httppost)
- HttpEntity entity = response.getEntity()
- is = entity.getContent()
- } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString())
- } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8)
- StringBuilder sb = new StringBuilder()
- String line = null
- while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- } is.close()
- result = sb.toString()
- } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString())
- } // try parse the string to a JSON object try { jArray = new JSONArray(result)
- Log.d("URL_SEARCH", "JSON: " + jArray.length())
- } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString())
- } return jArray
- }
-
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
- JSONObject json = new JSONObject()
- json.put("someKey", "someValue")
- CloseableHttpClient httpClient = HttpClientBuilder.create().build()
- try { HttpPost request = new HttpPost("http://yoururl")
- StringEntity params = new StringEntity(json.toString())
- request.addHeader("content-type", "application/x-www-form-urlencoded")
- request.setEntity(params)
- httpClient.execute(request)
- // handle response here...} catch (Exception ex) { // handle exception here} finally { httpClient.close()
- }
-
How can I read MYSQL Database from Android?
Thank you again!. This should work . details
Reactions - Positive 0, Negative 0, Others 0
- package com.Online.Test
- import java.io.IOException
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.util.EntityUtils
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- import android.app.Activity
- import android.os.AsyncTask
- import android.os.Bundle
- import android.widget.TextView
- import android.widget.Toast
- public class OnlineTestActivity extends Activity { /** Called when the activity is first created. */ TextView resultView
- HttpClient client
- JSONObject json
- String Dat
- @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
- setContentView(R.layout.main)
- resultView = (TextView) findViewById(R.id.tvjson)
- client = new DefaultHttpClient()
- try { json = RedData()
- } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
- } Dat = json.toString()
- new Read().onPostExecute(Dat)
- } public JSONObject RedData() throws ClientProtocolException, IOException, JSONException { HttpPost httppost = new HttpPost("//link.php")
- HttpResponse r = client.execute(httppost)
- // int status = r.getStatusLine().getStatusCode()
- //if (status == 200) { HttpEntity e = r.getEntity()
- String data = EntityUtils.toString(e)
- JSONArray jArray = new JSONArray(data)
- JSONObject last = jArray.getJSONObject(0)
- // 0 -> the last object return last
- // } else { // Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG)
- // return null
- //} } public class Read extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { json = RedData()
- //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG)
- return json.getString(arg0[0])
- } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
- } return null
- } @Override protected void onPostExecute(String data) { // TODO Auto-generated method stub resultView.setText(data)
- } }}
Other Reactions
- It would be even better if you explained the code and/or corrections.
-
HTTP POST using JSON in Java
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpClient httpClient = new DefaultHttpClient()
- try { HttpPost request = new HttpPost("http://yoururl")
- StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ")
- request.addHeader("content-type", "application/x-www-form-urlencoded")
- request.setEntity(params)
- HttpResponse response = httpClient.execute(request)
- // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
- }
-
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
- import org.apache.http.HttpResponse
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpPut
- import org.apache.http.entity.StringEntity
- import org.apache.http.impl.client.DefaultHttpClient
- import net.sf.json.JSONArray
- import net.sf.json.JSONObject
- public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
- for (int i = 0
- i < 5
- i++) { JSONObject jsonAddressObj = new JSONObject()
- jsonAddressObj.put("address1", "a")
- jsonAddressObj.put("address2", "b")
- jsonAddressObj.put("city", "c")
- jsonAddressObj.put("state", "d")
- jsonAddressObj.put("postalCode", "e")
- jsonAddressArray.add(jsonAddressObj)
- } System.out.println(jsonAddressArray)
- HttpClient httpClient = new DefaultHttpClient()
- try { HttpPut request = new HttpPut("http://yourAddressHere")
- StringEntity params =new StringEntity(jsonAddressArray.toString())
- request.setEntity(params)
- HttpResponse response = httpClient.execute(request)
- System.out.println(response.toString())
- // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
- }}
Positive Reactions
- Thanks, and it's good your pointing that out.
- But +1 for everything else!.
- I just put the values to my jsonAddressObj.
- I do not want to send harcoded values to any of the fields.
- "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
- OK.
- I need to send the following as http request.
- Yeh, I got the feeling we're not using the same library.
- I did take out the for loop.
- That helped me.
- I want the address to be fetched from the EditText.
- That is the reason i used txtAddress1.getText().toString().
- And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
- Have you read anything about these technologies or checked the documentation?
- That did that work for me.
- Are you referring to a post or a put ?
- Is it just me or you're never adding anything to your jsonAddressArray ?
- Passed the jsonAddressObj to jsonObjSend.
- Http request is quite broad.
- 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.
- 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.
- Here is what I want to do.
- it is a put method.
- Yeh your right...it's from the original code.
-
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
- import java.io.BufferedReader
- import java.io.IOException
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.net.URLEncoder
- import java.util.ArrayList
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.NameValuePair
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.HttpClient
- import org.apache.http.client.entity.UrlEncodedFormEntity
- import org.apache.http.client.methods.HttpGet
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.client.methods.HttpUriRequest
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.message.BasicNameValuePair
- import org.apache.http.protocol.HTTP
- import org.json.JSONException
- import org.json.JSONObject
- public class JsonClient { public enum RequestMethod{ GET, POST } private ArrayList <NameValuePair> params
- private ArrayList <NameValuePair> headers
- private String url
- private int responseCode
- private String message
- private JSONObject jsonResponse
- public JSONObject getResponse() { return jsonResponse
- } public String getErrorMessage() { return message
- } public int getResponseCode() { return responseCode
- } public JsonClient(String url) { this.url = url
- params = new ArrayList<NameValuePair>()
- headers = new ArrayList<NameValuePair>()
- } public void addParam(String name, String value) { params.add(new BasicNameValuePair(name, value))
- } public void addHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value))
- } public void execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""
- if(!params.isEmpty()){ combinedParams += "?"
- for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8")
- if(combinedParams.length() > 1) { combinedParams += "&" + paramString
- } else { combinedParams += paramString
- } } } HttpGet request = new HttpGet(url + combinedParams)
- //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
- } executeRequest(request, url)
- break
- } case POST: { HttpPost request = new HttpPost(url)
- //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
- } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8))
- } executeRequest(request, url)
- break
- } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient()
- HttpResponse httpResponse
- try { httpResponse = client.execute(request)
- responseCode = httpResponse.getStatusLine().getStatusCode()
- message = httpResponse.getStatusLine().getReasonPhrase()
- HttpEntity entity = httpResponse.getEntity()
- if (entity != null) { InputStream instream = entity.getContent()
- String response = convertStreamToString(instream)
- jsonResponse = new JSONObject(response)
- // Closing the input stream will trigger connection release instream.close()
- } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown()
- e.printStackTrace()
- } catch (IOException e) { client.getConnectionManager().shutdown()
- e.printStackTrace()
- }catch (JSONException e) { e.printStackTrace()
- } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is))
- StringBuilder sb = new StringBuilder()
- String line = null
- try { while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- } } catch (IOException e) { e.printStackTrace()
- } finally { try { is.close()
- } catch (IOException e) { e.printStackTrace()
- } } return sb.toString()
- }}
Positive Reactions
- Thanks for this.
Other Reactions
- I'll be able to use this in the future for sure.
-
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
- package com.hussain.StackOverFlow
- import java.io.BufferedReader
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.net.URI
- import java.util.ArrayList
- import org.apache.http.HttpResponse
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpGet
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.params.HttpConnectionParams
- import org.apache.http.params.HttpParams
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- 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")
- FarhaSameer1.parseFromJSONResponse(asd)
- } // 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 = ""
- try { HttpClient client = new DefaultHttpClient()
- HttpParams httpParameters = client.getParams()
- HttpConnectionParams.setConnectionTimeout(httpParameters, 5000)
- HttpConnectionParams.setSoTimeout(httpParameters, 5000)
- HttpConnectionParams.setTcpNoDelay(httpParameters, true)
- HttpGet request = new HttpGet()
- request.setURI(new URI(url))
- HttpResponse response = client.execute(request)
- InputStream ips = response.getEntity().getContent()
- BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"))
- StringBuilder sb = new StringBuilder()
- String s
- while (true) { s = buf.readLine()
- if (s == null || s.length() == 0) break
- sb.append(s)
- } buf.close()
- ips.close()
- result = sb.toString()
- } catch (Exception e) { e.printStackTrace()
- } return result
- } public static void parseFromJSONResponse(String respo) { JSONObject myjson
- try { myjson = new JSONObject(respo)
- JSONObject jsonObj1 = myjson.getJSONObject("feed")
- JSONArray jsonObj2 = jsonObj1.getJSONArray("entry")
- JSONObject jsonObj3 = jsonObj2.getJSONObject(0)
- System.out.println(jsonObj3.getJSONObject("content"))
- System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString())
- } catch (JSONException e) { e.printStackTrace()
- } } }
Negative Reactions
- a little help is here , URL_http://stackoverflow.com/questions/16544388 /converting-jsonarray-string-to-array/16544515#16544515.
Other Reactions
- ?
- @FarhaSameer : was it enough ?
-
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
- private class ParseTask extends AsyncTask<Params, Progress, Result> {
- @Override
- protected Result doInBackground(Params params) { // get url Params url = params[0]
- // create HttpClient etc. ... // get response, and parse json // return return result
- }
- @Override
- protected void onPostExecute(
- Result
- result) { // now when you have result from parsed json, // update application UI or whatever you need someEditText.setText(value_from_result)
- }
- }
Positive Reactions
- this work great, thanx...
Chart will be rendered here -
All usage scenarios for API commons-httpclient
-
HTTP POST using JSON in Java
None details
Reactions - Positive 0, Negative 0, Others 0
- String postUrl="www.site.com"
- // put in your urlGson gson= new Gson()
- HttpPost post = new HttpPost(postUrl)
- StringEntity postingString =new StringEntity(gson.toJson(pojo1))
- //convert your pojo to jsonpost.setEntity(postingString)
- post.setHeader("Content-type", "application/json")
- 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
- for (int i = 0
- i < type.length
- i++) { nameValuePairs.add(new BasicNameValuePair("type[]",type[i]))
- }
-
Retrieve Data by passing a parameter to url in Android
-
When using JSON in Fragments the app is not responding in Android Development
None details
Reactions - Positive 0, Negative 0, Others 0
- 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
- class TheTask extends AsyncTask<String, String, String> {
- @override
- protected String doInbackground(String... params) {
- String _response = null
- try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
- HttpPost httpPost = new HttpPost(params[0])
- HttpResponse httpResponse = httpClient.execute(httpPost)
- HttpEntity httpEntity = httpResponse.getEntity()
- _response = EntityUtils.toString(httpEntity)
- } catch (Exception e) {
- e.printStacktrace()
- }
- return _response
- }
- @Override
- protected void onPostExecute(
- String result) { // TODO Auto-generated method stub super.onPostExecute(result)
- Log.i(".......", result)
- }
- }
-
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
- HttpClient client = new DefaultHttpClient()
- HttpUriRequest request
- request = new HttpPost(<-URL->)
- StringEntity entity = new StringEntity(<-Your JSON string->)
- ((HttpPost) request).setEntity(entity)
- ((HttpPost) request).setHeader("Content-Type", "application/json")
- HttpResponse response = client.execute(request)
- HttpEntity entity = response.getEntity()
Negative Reactions
- keep giving me the same error :(.
- i dont know what a stacktrace is, i feel really bad.
- Hi , i get an error in HttpResponse response client.execute(request); the error is a null pointer exception.
Other Reactions
- ?
- can u send ur stacktrace??
- try using above code.
- 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
- @Overrideprotected void onPostExecute(Integer result) { pd.dismiss()
- // Extract Token from JSON stream try { JSONObject root = new JSONObject(jsonTokenStream)
- twitterToken = root.getString("access_token")
- } catch (Exception e) { Log.e("loadTwitterToken", "onPost Error:" + e.getMessage())
- } twitterText.setText("Got Token!")
- // 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()
- }
Positive Reactions
- I've made strides in the code.
- +1 save my lots of search and time..
- Thanks for that @Priyanka.
- So it has authorized properly, but stops there.
- I appreciate your help so far.
- Thanks for the explanation @Priyanka!
- 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
- Again, it still doesn't crash or show errors, but I get as far as the status telling me "Got Token!"
- It should be the last blocks in the file.
- @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.
- I've found that I needed to change the XML TextView to ListView and drop the ScrollView.
Other Reactions
- Can you tell if I set up the parse properly to output a list of tweets from my updated java?
- I can tell I'm close.
- 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
- JSONObject json = new JSONObject()
- json.put("someKey", "someValue")
- CloseableHttpClient httpClient = HttpClientBuilder.create().build()
- try { HttpPost request = new HttpPost("http://yoururl")
- StringEntity params = new StringEntity(json.toString())
- request.addHeader("content-type", "application/x-www-form-urlencoded")
- request.setEntity(params)
- httpClient.execute(request)
- // handle response here...} catch (Exception ex) { // handle exception here} finally { httpClient.close()
- }
-
How to make a "raw" string out of JSON in Java
None details
Reactions - Positive 0, Negative 0, Others 0
- public static JSONArray getJSONArrayFromURL(String url) { // initialize InputStream is = null
- String result = ""
- JSONArray jArray = null
- Log.d("URL_SEARCH", url)
- // http post try { HttpClient httpclient = new DefaultHttpClient()
- HttpPost httppost = new HttpPost(url)
- HttpResponse response = httpclient.execute(httppost)
- HttpEntity entity = response.getEntity()
- is = entity.getContent()
- } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString())
- } // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8)
- StringBuilder sb = new StringBuilder()
- String line = null
- while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- } is.close()
- result = sb.toString()
- } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString())
- } // try parse the string to a JSON object try { jArray = new JSONArray(result)
- Log.d("URL_SEARCH", "JSON: " + jArray.length())
- } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString())
- } return jArray
- }
-
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
- package com.hussain.StackOverFlow
- import java.io.BufferedReader
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.net.URI
- import java.util.ArrayList
- import org.apache.http.HttpResponse
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpGet
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.params.HttpConnectionParams
- import org.apache.http.params.HttpParams
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- 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")
- FarhaSameer1.parseFromJSONResponse(asd)
- } // 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 = ""
- try { HttpClient client = new DefaultHttpClient()
- HttpParams httpParameters = client.getParams()
- HttpConnectionParams.setConnectionTimeout(httpParameters, 5000)
- HttpConnectionParams.setSoTimeout(httpParameters, 5000)
- HttpConnectionParams.setTcpNoDelay(httpParameters, true)
- HttpGet request = new HttpGet()
- request.setURI(new URI(url))
- HttpResponse response = client.execute(request)
- InputStream ips = response.getEntity().getContent()
- BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"))
- StringBuilder sb = new StringBuilder()
- String s
- while (true) { s = buf.readLine()
- if (s == null || s.length() == 0) break
- sb.append(s)
- } buf.close()
- ips.close()
- result = sb.toString()
- } catch (Exception e) { e.printStackTrace()
- } return result
- } public static void parseFromJSONResponse(String respo) { JSONObject myjson
- try { myjson = new JSONObject(respo)
- JSONObject jsonObj1 = myjson.getJSONObject("feed")
- JSONArray jsonObj2 = jsonObj1.getJSONArray("entry")
- JSONObject jsonObj3 = jsonObj2.getJSONObject(0)
- System.out.println(jsonObj3.getJSONObject("content"))
- System.out.println("here ===>>>"+jsonObj3.getJSONObject("content").get("$t").toString())
- } catch (JSONException e) { e.printStackTrace()
- } } }
Negative Reactions
- a little help is here , URL_http://stackoverflow.com/questions/16544388 /converting-jsonarray-string-to-array/16544515#16544515.
Other Reactions
- ?
- @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
- 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
- HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 )
- //1 minuteHttpConnectionParams.setSoTimeout( httpParameters, 90000 )
- // 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
- HttpParams httpParams = new BasicHttpParams()
- HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8)
- HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8)
- HttpClient client = new DefaultHttpClient(httpParams)
- HttpPost request = new HttpPost(serverURL)
- StringEntity str = null
- String jsonString = gson.toJson(yourdata)
- str = new StringEntity(jsonString, HTTP.UTF_8)
- request.setEntity(str)
- request.setHeader("Accept", "application/json")
- request.setHeader("Content-type", "application/json")
- 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
- package com.inzane.shoapp.activity
- import java.io.BufferedReader
- import java.io.IOException
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.io.UnsupportedEncodingException
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.impl.client.DefaultHttpClient
- import org.json.JSONException
- import org.json.JSONObject
- import android.util.Log
- public class JSONParser {static InputStream is = null
- static JSONObject jObj = null
- static String json = ""
- // constructorpublic JSONParser() {}public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient()
- HttpPost httpPost = new HttpPost(url)
- HttpResponse httpResponse = httpClient.execute(httpPost)
- HttpEntity httpEntity = httpResponse.getEntity()
- is = httpEntity.getContent()
- } catch (UnsupportedEncodingException e) { e.printStackTrace()
- } catch (ClientProtocolException e) { e.printStackTrace()
- } catch (IOException e) { e.printStackTrace()
- } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8)
- StringBuilder sb = new StringBuilder()
- String line = null
- while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- System.out.println(line)
- } is.close()
- json = sb.toString()
- } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString())
- } // try parse the string to a JSON object try { jObj = new JSONObject(json)
- } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString())
- System.out.println("error on parse data in jsonparser.java")
- } // return JSON String return jObj
- }}
-
JSONArray cannot be converted to JSONObject given a string
None details
Reactions - Positive 0, Negative 0, Others 0
- ... public JSONObject getJSONfromURL (String url){ //HTTP call try{ URLConnection connection = new URL(url).openConnection()
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16)
- StringBuffer builder = new StringBuffer()
- String line
- while ((line = reader.readLine()) != null) { builder.append(line).append("\n")
- } String blah = builder.toString()
- //Parsing string into JSONArray JSONArray data = new JSONArray(new String(blah))
- for(int i=0
- i < data.length()
- i++) { object = data.getJSONObject(i)
- String id = object.getString("id")
- String value = object.getString("name")
- Log.d("Item name: ", value)
- } } catch(Exception e){ Log.e("Http Error","Error in http connection " + e.toString())
- } return object
- }..
-
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
- import java.io.BufferedReader
- import java.io.IOException
- import java.io.InputStream
- import java.io.InputStreamReader
- import java.net.URLEncoder
- import java.util.ArrayList
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.NameValuePair
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.HttpClient
- import org.apache.http.client.entity.UrlEncodedFormEntity
- import org.apache.http.client.methods.HttpGet
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.client.methods.HttpUriRequest
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.message.BasicNameValuePair
- import org.apache.http.protocol.HTTP
- import org.json.JSONException
- import org.json.JSONObject
- public class JsonClient { public enum RequestMethod{ GET, POST } private ArrayList <NameValuePair> params
- private ArrayList <NameValuePair> headers
- private String url
- private int responseCode
- private String message
- private JSONObject jsonResponse
- public JSONObject getResponse() { return jsonResponse
- } public String getErrorMessage() { return message
- } public int getResponseCode() { return responseCode
- } public JsonClient(String url) { this.url = url
- params = new ArrayList<NameValuePair>()
- headers = new ArrayList<NameValuePair>()
- } public void addParam(String name, String value) { params.add(new BasicNameValuePair(name, value))
- } public void addHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value))
- } public void execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""
- if(!params.isEmpty()){ combinedParams += "?"
- for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8")
- if(combinedParams.length() > 1) { combinedParams += "&" + paramString
- } else { combinedParams += paramString
- } } } HttpGet request = new HttpGet(url + combinedParams)
- //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
- } executeRequest(request, url)
- break
- } case POST: { HttpPost request = new HttpPost(url)
- //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue())
- } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8))
- } executeRequest(request, url)
- break
- } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient()
- HttpResponse httpResponse
- try { httpResponse = client.execute(request)
- responseCode = httpResponse.getStatusLine().getStatusCode()
- message = httpResponse.getStatusLine().getReasonPhrase()
- HttpEntity entity = httpResponse.getEntity()
- if (entity != null) { InputStream instream = entity.getContent()
- String response = convertStreamToString(instream)
- jsonResponse = new JSONObject(response)
- // Closing the input stream will trigger connection release instream.close()
- } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown()
- e.printStackTrace()
- } catch (IOException e) { client.getConnectionManager().shutdown()
- e.printStackTrace()
- }catch (JSONException e) { e.printStackTrace()
- } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is))
- StringBuilder sb = new StringBuilder()
- String line = null
- try { while ((line = reader.readLine()) != null) { sb.append(line + "\n")
- } } catch (IOException e) { e.printStackTrace()
- } finally { try { is.close()
- } catch (IOException e) { e.printStackTrace()
- } } return sb.toString()
- }}
Positive Reactions
- Thanks for this.
Other Reactions
- 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
- import org.apache.http.HttpResponse
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpPut
- import org.apache.http.entity.StringEntity
- import org.apache.http.impl.client.DefaultHttpClient
- import net.sf.json.JSONArray
- import net.sf.json.JSONObject
- public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
- for (int i = 0
- i < 5
- i++) { JSONObject jsonAddressObj = new JSONObject()
- jsonAddressObj.put("address1", "a")
- jsonAddressObj.put("address2", "b")
- jsonAddressObj.put("city", "c")
- jsonAddressObj.put("state", "d")
- jsonAddressObj.put("postalCode", "e")
- jsonAddressArray.add(jsonAddressObj)
- } System.out.println(jsonAddressArray)
- HttpClient httpClient = new DefaultHttpClient()
- try { HttpPut request = new HttpPut("http://yourAddressHere")
- StringEntity params =new StringEntity(jsonAddressArray.toString())
- request.setEntity(params)
- HttpResponse response = httpClient.execute(request)
- System.out.println(response.toString())
- // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
- }}
Positive Reactions
- Thanks, and it's good your pointing that out.
- But +1 for everything else!.
- I just put the values to my jsonAddressObj.
- I do not want to send harcoded values to any of the fields.
- "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
- OK.
- I need to send the following as http request.
- Yeh, I got the feeling we're not using the same library.
- I did take out the for loop.
- That helped me.
- I want the address to be fetched from the EditText.
- That is the reason i used txtAddress1.getText().toString().
- And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
- Have you read anything about these technologies or checked the documentation?
- That did that work for me.
- Are you referring to a post or a put ?
- Is it just me or you're never adding anything to your jsonAddressArray ?
- Passed the jsonAddressObj to jsonObjSend.
- Http request is quite broad.
- 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.
- 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.
- Here is what I want to do.
- it is a put method.
- 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
- nameValuePairs.add(new BasicNameValuePair("devices[]", device1))
- nameValuePairs.add(new BasicNameValuePair("devices[]", device2))
- nameValuePairs.add(new BasicNameValuePair("devices[]", device3))
Negative Reactions
- 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
- 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
- HttpResponse httpResponse = httpClient.execute(httpPut)
- 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
- HttpResponse mHttpResponse = mHttpClient.execute(httppost)
- StatusLine status = mHttpResponse.getStatusLine()
- 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
- String jsonString = EntityUtils.toString(response.getEntity())
Positive Reactions
- I have tried implementing you code ANR !!!
- If you have the Log please paste it in your question and also please update your question with the new code.
Other Reactions
- !.
- 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
- 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
- HttpGet httpget = new HttpGet(url)
- httpget.addHeader("Cookie", "JSESSIONID=...")
Positive Reactions
- 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.
- Thanks so much.
- So I can do something like method.setRequestHeader("Cookie", "JSESSIONID=F7B89109EABD2FFD58A0096AF2123199"); and it should work?
- Thanks.
Negative Reactions
- I used Selenium to "login" then capture the JSESSION ID and pass that into my httpget.addHeader("Cookie", "JSESSIONID=" + jsessionIdVal);.
Other Reactions
- This allowed me to get past the login screen.
- Ach, I see now that you ask for HttpClient 4.
- And how can I use HttpMethod and GetMethod?
- Not that it makes that much of a difference.
- The names I used are for HttpClient 3.
- I've seen this before but couldn't figure out what postData was in the question and answers.
- I already added the JAR files that I downloaded from Apache website you linked to but now sure what import to call.
- 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
- public String post(String str) { String result = ""
- try { HttpParams httpParameters = new BasicHttpParams()
- int timeoutConnection = 3000
- HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection)
- int timeoutSocket = 5000
- HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket)
- DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters)
- HttpPost postRequest = new HttpPost(SERVER_ADDRESS)
- StringEntity input = new StringEntity(str)
- input.setContentType("application/json")
- postRequest.setEntity(input)
- HttpResponse response = httpClient.execute(postRequest)
- result = getResult(response).toString()
- httpClient.getConnectionManager().shutdown()
- } catch (Exception e) { System.out.println(e.getMessage())
- } return result
- }private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException { StringBuilder result = new StringBuilder()
- BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024)
- String output
- while ((output = br.readLine()) != null) result.append(output)
- return result
- }
Positive Reactions
- Thanks, didn't think about having this going in the background via threads.
- You are welcome.
- Thanks for the code too.
- hope that it is helpful for you.
Other Reactions
- 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
- private class ParseTask extends AsyncTask<Params, Progress, Result> {
- @Override
- protected Result doInBackground(Params params) { // get url Params url = params[0]
- // create HttpClient etc. ... // get response, and parse json // return return result
- }
- @Override
- protected void onPostExecute(
- Result
- result) { // now when you have result from parsed json, // update application UI or whatever you need someEditText.setText(value_from_result)
- }
- }
Positive Reactions
- 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
- HttpResponse response = httpClient.execute(request)
- String tekst = EntityUtils.toString( response.getEntity() )
Positive Reactions
- Thanks for your response.
Negative Reactions
- Unfortunately this gives the same JSONException.
-
HttpPost response doesn't return the json object
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpResponse httpResponse = httpClient.execute(httpPost)
- 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
- package com.Online.Test
- import java.io.IOException
- import org.apache.http.HttpEntity
- import org.apache.http.HttpResponse
- import org.apache.http.client.ClientProtocolException
- import org.apache.http.client.HttpClient
- import org.apache.http.client.methods.HttpPost
- import org.apache.http.impl.client.DefaultHttpClient
- import org.apache.http.util.EntityUtils
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- import android.app.Activity
- import android.os.AsyncTask
- import android.os.Bundle
- import android.widget.TextView
- import android.widget.Toast
- public class OnlineTestActivity extends Activity { /** Called when the activity is first created. */ TextView resultView
- HttpClient client
- JSONObject json
- String Dat
- @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)
- setContentView(R.layout.main)
- resultView = (TextView) findViewById(R.id.tvjson)
- client = new DefaultHttpClient()
- try { json = RedData()
- } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
- } Dat = json.toString()
- new Read().onPostExecute(Dat)
- } public JSONObject RedData() throws ClientProtocolException, IOException, JSONException { HttpPost httppost = new HttpPost("//link.php")
- HttpResponse r = client.execute(httppost)
- // int status = r.getStatusLine().getStatusCode()
- //if (status == 200) { HttpEntity e = r.getEntity()
- String data = EntityUtils.toString(e)
- JSONArray jArray = new JSONArray(data)
- JSONObject last = jArray.getJSONObject(0)
- // 0 -> the last object return last
- // } else { // Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG)
- // return null
- //} } public class Read extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { json = RedData()
- //Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG)
- return json.getString(arg0[0])
- } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace()
- } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace()
- } return null
- } @Override protected void onPostExecute(String data) { // TODO Auto-generated method stub resultView.setText(data)
- } }}
Other Reactions
- 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
- HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES)
-
JSON Object returns a null pointer
-
HTTP POST using JSON in Java
None details
Reactions - Positive 0, Negative 0, Others 0
- HttpClient httpClient = new DefaultHttpClient()
- try { HttpPost request = new HttpPost("http://yoururl")
- StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ")
- request.addHeader("content-type", "application/x-www-form-urlencoded")
- request.setEntity(params)
- HttpResponse response = httpClient.execute(request)
- // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
- }
-
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
- params.add(new BasicNameValuePair("apikey", apikey)
Positive Reactions
- 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
- 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
- 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
- String jsontext = EntityUtils.toString(response.getEntity())