Display JSON response from POST request

霸气de小男生 提交于 2019-12-13 09:34:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!