当前位置: 首页 > 知识库问答 >
问题:

无法在Android HTTP POST调用中将内容类型更改为application/x-www-form-urlencoded

曹鹏海
2023-03-14

我们的服务器在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的请求。您可以看到,尽管我在这两种情况下都将内容类型设置为“application/x-www-form-urlencoded”,但请求内容类型为“application/json”:

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

有人知道我为什么不能更改内容类型吗?我知道以前也有人问过类似的问题,所以我都试过了,但都没有用。非常感谢你的帮助。

谢谢!

共有1个答案

柳仲卿
2023-03-14

为什么不使用:

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

这对我有用。

 类似资料: