0

我们的服务器在 POST 调用中需要 'application/x-www-form-urlencoded' 内容类型,但是当我将标头设置为 'application/x-www-form-urlencoded' 时,它返回 400 错误请求。这是我使用 HttpPost 的代码:

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    HttpResponse responseobj = httpClient.execute(httpPost);
    InputStream is = null;
    HttpEntity entity = responseobj.getEntity();
    is = entity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
    }
    is.close();

这是我使用 HttpsUrlConnection 的代码:

    URL urlToRequest;
    urlToRequest = new URL(url);
    HttpsURLConnection conn = (HttpsURLConnection) urlToRequest.openConnection();
    String postParams = getEncodedPostParams(params);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setFixedLengthStreamingMode(postParams.getBytes().length);
    conn.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(postParams);
    writer.close();
    os.close();
    conn.connect();

这是 Charles Proxy 上的请求。您可以看到,虽然我在这两种情况下都将 content-type 设置为 'application/x-www-form-urlencoded',但请求的 content-type 是 'application/json':

https://myurl/
Complete
400 Bad Request
HTTP/1.1
POST
application/json

有谁知道为什么我不能更改内容类型?我知道以前曾在 SO 上提出过类似的问题,但我尝试了所有这些问题都无济于事。您的帮助将不胜感激。

谢谢!

4

1 回答 1

1

为什么不使用:

con.setRequestProperty("Content-Type",....) 

它对我有用。

于 2013-07-04T09:55:28.837 回答