saber saber - 1 month ago 20
reST (reStructuredText) Question

Post Json from android client to server and get response

I'm new to android network programming and I want to post some Json formatted data from an android to a server and get response back to android client using same

HttpURLConnection
which used for post data.

Here is my post code:

public void post() throws IOException {

URL url = createEndpointUrl();

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod(POST);
conn.setDoInput(true);
conn.setDoOutput(true);

String query = createQueryParameters();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

writer.write(query);
writer.flush();
writer.close();

// Here i want to get operation
// result (response) from server
.
.
.
//
os.close();

conn.disconnect();
}

Answer

Get response :

 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
 String decodedString;
 StringBuilder stringBuilder = new StringBuilder();
 while ((decodedString = in.readLine()) != null) {
       stringBuilder.append(decodedString);
 }
 in.close();
 /*YOUR RESPONSE */
 String response = stringBuilder.toString();