I usually send a message (server response is a JSON object):
try { postJSON.put("param1", param1); postJSON.put("param2",param2); } catch (JSONException e) { e.printStackTrace(); } String result = JSONGetHTTP.postData(url); if (result != null) { try { JSONObject jObjec = new JSONObject(result); } } catch (JSONException e) { Log.e(TAG, "Error setting data " + e.toString()); } }
And postData:
public static String postData(String url, JSONObject obj) { // Create a new HttpClient and Post Header HttpClient httpclient = null; try { HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, 30000); HttpConnectionParams.setSoTimeout(myParams, 30000); httpclient = new DefaultHttpClient(myParams); } catch (Exception e) { Log.e("POST_DATA", "error in httpConnection"); e.printStackTrace(); } InputStream is = null; try { HttpPost httppost = new HttpPost(url.toString()); //Header here httppost.setHeader(); StringEntity se = new StringEntity(obj.toString()); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); // // Do something with response... is = entity.getContent(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // convert response to string BufferedReader reader = null; String result = null; try { 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"); } result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } finally { try { if (reader != null) reader.close(); if (is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } } if (result != null) { try { @SuppressWarnings("unused") JSONObject jObjec = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } } return result; }
Hope this helps
source share