我必须发送包含参数'username'和'password'的POST请求。
我相信我在下面这样做了:
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;
}
下一步说我将收到一个带有“id”和“验证”的JSON响应。如何显示/解析此JSON响应?我试过做`Log.d(“Result”,httpPost.toString());但这显然不起作用,我不知道我在这做什么。
有人可以帮忙吗?
答案 0 :(得分:0)
调用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());
如果服务器返回JSON响应然后将builder.toString()
转换为JSONObject并使用键从中获取所有值