如何在android中发布(参数)并从Httpclient和Httppost获取响应

时间:2014-11-21 11:02:44

标签: java android json http-post apache-httpclient-4.x

我希望来自网络服务器的正确回复。我的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();
}

有什么不对吗?有人请帮助我。提前致谢

1 个答案:

答案 0 :(得分:0)

尝试替换此代码:

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);  

希望有所帮助