2012-04-21 120 views
3

我正在爲我的Android手機構建一個小應用程序,使用非常基本的REST界面將文本消息轉發到網絡服務器。Java HttpClient更改內容類型?

我正在使用android 4.0.3 SDK。我使用Django和Django restframework軟件包在python中開發了web服務。該設置完全開箱即用。基本上有一個端點接收持有消息信息(sender,body,date)的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<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發佈消息到我的web服務時,某些時候內容類型從'application/json'變爲'application/json,application/json'。在頭部循環日誌條目仍輸出正確的價值觀對每個頭,然而,Web服務將返回此錯誤消息:

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

我百思不得其解,任何幫助是值得歡迎的。

+0

爲什麼你寫兩個 「內容類型」 頭?一旦與http.setHeader和其他通過實體。也許這是錯誤的原因。 – SJuan76 2012-04-21 23:12:59

+0

據我瞭解,第二個(在StringEntity)只是設置實體的解碼,並不影響後標題。我已經通過不添加帖子標題來測試。在這種情況下,結束於請求中的標題是標準文本/普通標題。 – Bart 2012-04-21 23:18:03

+1

不是說我確信這一點,但我會嘗試沒有實體。除此之外,HTTP嗅探器(如wireshark)可以幫助您診斷故障是在客戶端還是在服務器中。 – SJuan76 2012-04-21 23:20:27

回答

6

更改此:

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

感謝隊友!這就是我所需要的。 @ SJuan76你是對的,歡呼傢伙,非常有幫助! – Bart 2012-04-22 01:14:40

+3

應該是'se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,「application/json」));' – Danpe 2014-10-12 19:54:20