【问题标题】:Java HttpClient changing content-type?Java HttpClient 更改内容类型?
【发布时间】:2012-04-21 23:08:58
【问题描述】:

我正在为我的 Android 手机构建一个小应用程序,以使用非常基本的 REST 接口将文本消息转发到网络服务器。

我正在使用 android 4.0.3 SDK。我使用 Django 和 Django restframework 包在 python 中开发了 web 服务。设置完全开箱即用。基本上有一个端点接收包含消息信息(发件人、正文、日期)的 JSON 对象的 POST。我已经通过以下命令使用 cURL 测试了该服务:

curl -X POST -H 'Content-Type: application/json' --data '{"sender":"+xxxxxxxx", "body": "test", "send_date":"2011-03-20 16:32:02"}' http://[...]/messages.json

这一切都很好,我得到了预期的响应:

{"body": "test", "send_date": "2011-03-20T16:32:02", "id": 25, "sender": "+xxxxxxxxxx"}

现在我设置了安卓应用。它是一个简单的 BroadcastReceiver 子类,包含一个私有 AsyncTask 类:

private class httpPost extends AsyncTask<String, Void, JSONObject> {
    protected JSONObject doInBackground(String... args) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);

        String url = args[0];
        String json=args[1];            
        JSONObject JSONResponse = null;
        InputStream contentStream = null;
        String resultString = "";

        try {
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-Type", "application/json");
            httppost.setHeader("Accept", "application/json");

            StringEntity se = new StringEntity(json); 
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se);

            for (int i=0;i<httppost.getAllHeaders().length;i++) {
                Log.v("set header", httppost.getAllHeaders()[i].getValue());
            }

            HttpResponse response = httpclient.execute(httppost);

            // Do some checks to make sure that the request was processed properly
            Header[] headers = response.getAllHeaders();
            HttpEntity entity = response.getEntity();
            contentStream = entity.getContent();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            contentStream.close();
            resultString = sb.toString();
        }catch(Exception e){
            e.printStackTrace();
        }

        Log.v("log", resultString);
        return new JSONObject();
    }


}

如您所见,我刚刚开始熟悉 Java 和 android SDK,所以请多多包涵。这个设置实际上在我构建的另一个应用程序中运行良好,用于将 JSON 字符串发送到 Neo4J Web 服务。

问题是,当我通过 Android 将消息发布到我的网络服务时,有时内容类型会从“应用程序/json”更改为“应用程序/json,应用程序/json”。 headers 循环中的日志条目仍然为每个 header 输出正确的值,但是,webservice 返回此错误消息:

{"error": "Unsupported media type in request 'application/json, application/json'."}

我很困惑,欢迎任何帮助。

【问题讨论】:

  • 为什么要写两个“Content-Type”标题?一次使用 http.setHeader,另一次使用实体。也许这是错误的原因。
  • 据我了解,第二个(在StringEntity处)只是设置实体的解码,不影响post headers。我通过不添加帖子标题对此进行了测试。在这种情况下,请求中的标头是标准的 text/plain 标头。
  • 并不是说我对此很确定,但我会在没有实体的情况下尝试。除此之外,HTTP 嗅探器(如wireshark)可以帮助您诊断故障是在客户端还是在服务器端。
  • 现在下载wireshark,看看能给我们带来什么。非常感谢您的指点

标签: java android django http-post


【解决方案1】:

改变这个:

StringEntity se = new StringEntity(json); 
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);

仅此:

httppost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));

【讨论】:

  • 谢谢老兄!!这就是我所需要的。 @SJuan76 你也是对的,干杯,非常有帮助!
  • 应该是se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  • 添加 HTTP.UTF_8 作为字符集解决了我的问题...谢谢 :)
【解决方案2】:

简单:

import org.apache.http.client.methods.HttpPost;

httppost.setEntity(new StringEntity(json.toString(), org.apache.http.entity.ContentType.APPLICATION_JSON));

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2012-09-22
    • 2012-09-22
    • 2017-11-26
    • 1970-01-01
    相关资源
    最近更新 更多