问题
I have to send a POST request containing the parameters 'username' and 'password'.
I believe I did this below:
public static void execute() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("username", login.getText().toString());
comment.put("password", password.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://www.example.com", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
Log.d("Result", httpPost.toString());
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The next step says that I will receive a JSON response with an 'id' and a 'verification'. How do I display/parse this JSON response? I tried doing ` Log.d("Result", httpPost.toString()); but that clearly doesn't work and I have no idea what I am doing here.
Can someone please help?
回答1:
Read response from server after calling DefaultHttpClient().execute
:
HttpResponse response=makeRequest("http://www.example.com", json);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line);
}
Log.d("Result","Response :: "+ builder.toString());
if server returning JSON response then convert builder.toString()
to JSONObject and get all values from it using keys
来源:https://stackoverflow.com/questions/28508657/display-json-response-from-post-request