我们的服务器在POST调用时需要'application / x-www-form-urlencoded'内容类型,但是当我将标头设置为'application / x-www-form-urlencoded'时,它会返回400 Bad Request。这是我使用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的请求。你可以看到虽然我在两种情况下都将内容类型设置为'application / x-www-form-urlencoded',但请求内容类型是'application / json':
https://myurl/
Complete
400 Bad Request
HTTP/1.1
POST
application/json
有谁知道为什么我无法更改内容类型?我知道之前已经问过类似的问题而且我已经尝试了所有这些问题无济于事。非常感谢您的帮助。
谢谢!
答案 0 :(得分:1)
为什么不使用:
con.setRequestProperty("Content-Type",....)
它对我有用。