Server takes two parameters: String
and JSON
.
Prompt, correctly I transfer JSON
and String in POST request?
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("my_url");
List parameters = new ArrayList(2);
JSONObject jsonObject = new JSONObject();
jsonObject.put("par_1", "1");
jsonObject.put("par_2", "2");
jsonObject.put("par_3", "3");
parameters.add(new BasicNameValuePair("action", "par_action"));
parameters.add(new BasicNameValuePair("data", jsonObject.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("Server Application", EntityUtils.toString(httpResponse.getEntity())+" "+jsonObject.toString());
} catch (UnsupportedEncodingException e) {
Log.e("Server Application", "Error: " + e);
} catch (ClientProtocolException e) {
Log.e("Server Application", "Error: " + e);
} catch (IOException e) {
Log.e("Server Application", "Error: " + e);
} catch (JSONException e) {
e.printStackTrace();
}
I am not exactly sure what your issue is, but here is how I send JSON (using your data example).
Android / JSON building:
Android / Sending JSON:
PHP / Server Side:
I really see much better having a RestClient class in order to have more code scalability,but basically I think your code is good, for basic solutions.Here I post a proper RestClient class, wich implements a POST or a GET:
With this you can easily do a POST like this, for example: