问题描述
我要发送包含参数用户名和密码POST请求。
I have to send a POST request containing the parameters 'username' and 'password'.
我相信我这样做如下:
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;
}
接下来说,我将收到一个'身份证'和'确认'JSON响应。如何显示/解析此JSON响应?我试着做`Log.d(结果,httpPost.toString());但是这显然不工作,我不知道我在做什么在这里。
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.
有人可以帮忙吗?
推荐答案
读取调用响应后从服务器 DefaultHttpClient()执行
:
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());
如果服务器返回JSON响应,那么转换 builder.toString()
来的JSONObject并用钥匙从它那里得到的所有值
if server returning JSON response then convert builder.toString()
to JSONObject and get all values from it using keys
这篇关于从POST请求显示JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!