【问题标题】:Cannot change CONTENT_TYPE to application/x-www-form-urlencoded in Android HTTP POST call无法在 Android HTTP POST 调用中将 CONTENT_TYPE 更改为 application/x-www-form-urlencoded
【发布时间】:2013-06-26 11:13:31
【问题描述】:

我们的服务器在 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 上提出过类似的问题,但我尝试了所有这些问题都无济于事。您的帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: android post http-post httpurlconnection android-networking


    【解决方案1】:

    为什么不使用:

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

    它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 2020-04-21
      • 2019-10-26
      • 2014-03-30
      • 2017-09-22
      • 2018-08-18
      • 1970-01-01
      相关资源
      最近更新 更多