Apache HttpClient JSON Post

Apache HttpClient JSON Post

我尝试在应用程序中使用 HttpClient 4.4 直接发送 JSON 字符串 (SWT/JFace) :

    public String postJSON(String urlToRead,Object o) throws ClientProtocolException, IOException {
    String result="";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost postRequest = new HttpPost(urlToRead);
        postRequest.setHeader("content-type", "application/x-www-form-urlencoded");
        //postRequest.setHeader("Content-type", "application/json");

        //{"mail":"admin@localhost", "password":"xyz"}
        String jsonString=gson.toJson(o);
        StringEntity params =new StringEntity(jsonString);
        params.setContentType("application/json");
        params.setContentEncoding("UTF-8");
        postRequest.setEntity(params);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        result = httpClient.execute(postRequest, responseHandler);
    }finally {
        httpClient.close();;
    }
    return result;
}

我尝试使用 $POST

从服务器 (Apache/PHP) 获取响应

$POST的正确内容应该是:

array("mail"=>"admin@localhost","password"=>"xyz")

当我使用content-type : application/x-www-form-urlencoded

$POST内容为:

array( "{"mail":"admin@localhost","password":"xyz"}"=> )

当我使用content-type : application/json

$POST 为空:array()

有没有办法用 HttpClient post JSON 字符串,或者我应该使用 ArrayList<NameValuePair> 并在实体中添加对象的每个成员?

我把"NameValuePair"解决方案(不在评论中,答案太长了),但我认为StringEntity能够理解JSON见 and there:

public String postJSON(String urlToRead,Object o) throws ClientProtocolException, IOException {
    String result="";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost postRequest = new HttpPost(urlToRead);
        postRequest.setHeader("content-type", "application/x-www-form-urlencoded");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        //{"mail":"admin@localhost", "password":"xyz"}    
        JsonElement elm= gson.toJsonTree(o);
        JsonObject jsonObj=elm.getAsJsonObject();
        for(Map.Entry<String, JsonElement> entry:jsonObj.entrySet()){
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().getAsString()));
        }
         postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        result = httpClient.execute(postRequest, responseHandler);
    }finally {
        httpClient.close();;
    }
    return result;
}

这样,$POST的内容就正确了:array("mail"=>"admin@localhost","password"=>"xyz")