简体   繁体   English

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

[英]how to post (parameters) and get the response from Httpclient and Httppost in android

I want correct response from web server. 我想要Web服务器的正确响应。 The structure of my json response is like this. 我的json响应的结构是这样的。

{
    "message": "Successfully",
    "profile": {
        "name": "myname",
        "mail": "mymail",
        "sex" : sex
    }
}

But I always get the response as below. 但是我总是得到如下响应。

{
    "message": "failed"
}

Below is my code. 下面是我的代码。

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

Is there anything wrong? 有什么问题吗? Anyone please help me. 有人请帮助我。 Thanks in advance 提前致谢

Try replace the code for this: 尝试为此替换代码:

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

hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM