我想从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);
希望能帮助到你