Java HttpClient改变内容类型?

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

我正在使用android 4.0.3 SDK。 我使用Django和Django restframework包在python中开发了webservice。 设置完全开箱即用。 基本上有一个端点接收包含消息信息(发送者,正文,日期)的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"}

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

 private class httpPost extends AsyncTask { 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将消息发布到我的webservice时,在某些时候内容类型从’application / json’变为’application / json,application / json’。 header循环中的日志条目仍然为每个标头输出正确的值,但是,webservice返回以下错误消息:

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

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

改变这个:

 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));