[英]Using HttpClient and HttpPost in Android with post parameters
[英]how to post (parameters) and get the response from Httpclient and Httppost in android
我想要Web服务器的正确响应。 我的json响应的结构是这样的。
{
"message": "Successfully",
"profile": {
"name": "myname",
"mail": "mymail",
"sex" : sex
}
}
但是我总是得到如下响应。
{
"message": "failed"
}
下面是我的代码。
String url ="myurlXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
JSONObject json1 = new JSONObject();
json1.put("name", myname);
json1.put("mail", mymail);
json1.put("sex", sex);
HttpClient client = new DefaultHttpClient();
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-type", "application/json");
post1.setHeader("Accept", "application/json");
post1.setEntity(new StringEntity(json1.toString(), "UTF-8"));
HttpResponse httpresponse = client.execute(post1);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
有什么问题吗? 有人请帮助我。 提前致谢
尝试为此替换代码:
JSONObject json2 = new JSONObject();
JSONObject json1 = new JSONObject();
json1.put("name", myname);
json1.put("mail", mymail);
json1.put("sex", sex);
json2.put("message", "Successfully");
json2.put("profile", json1);
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-type", "application/json");
post1.setHeader("Accept", "application/json");
post1.setEntity(new StringEntity(json2.toString(), "UTF-8"));
HttpResponse httpresponse = client.execute(post1);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.