2012-01-23 116 views
8

我想發送JSON格式的數據到使用Java的服務器。信息正在到達服務器,但服務器正在響應「錯誤請求」。Java:預覽HttpPost請求

HttpPost httpost = new HttpPost(path); 

    StringEntity se = new StringEntity(JSONRequest); 

    //sets the post request as the resulting string 
    httpost.setEntity(se); 

    //sets a request header so the page receving the request will know what to do with it 
    httpost.setHeader("Accept", "application/json"); 
    httpost.setHeader("Content-type", "application/json;charset=utf8"); 
    HttpResponse response = httpclient.execute(httpost); 

這是我的請求的基本設置。這裏是JSONData:

{"clientApplicationDto":{"AuthenticationToken":"","BrandId":12,"MobileDeviceApplicationId":0},"mobileDeviceInfo":{"CarrierName":"MTN-SA","OsVersion":"2.2.2","ClientApplicationVersion":"TEST","DeviceManufacturer":"HTC","DeviceName":"HTC Desire","DeviceUniqueId":"1e9766fa2ef4c53a","OsName":"8","ClientApplicationTypeId":3}} 

如果這看起來你的權利很多,我將開始發送垃圾郵件的管理員,但現在,我需要知道,如果我失去了一些東西。

+1

嗯..對於初學者來說,'StringEntity'(或者說任何'AbstractHttpEntity'子類)的內容類型,它會被默認設置爲常量'HTTP.PLAIN_TEXT_TYPE',使用'HTTP.DEFAULT_CONTENT_CHARSET'作爲字符集。考慮通過調用se#setContentType(「application/json; charset = utf-8」)來設置Content-type。順便說一句,你的JSON看起來很完美。 – Jens

+0

只是爲了檢查它是否存在帖子或java代碼的問題,您是否嘗試過像Chrome REST控制檯那樣的請求? https://chrome.google.com/webstore/detail/cokgbflfommojglbmbpenpphppikmonn – Dori

回答

9

我發現這個問題...服務器是內容類型標題和內容格式

httpost.setHeader("Content-type", "application/json;charset=utf8"); 

需要更換時至

httpost.setHeader("Content-type", "application/json; charset=utf-8"); 

和 StringEntity本身極爲敏感=新StringEntity(JSONRequest);

需要更換時至

 StringEntity se = new StringEntity(JSONRequest,"utf-8"); 

由於延,一個評論把我推到正確的方向。

+0

謝謝,你救了我的一天! –

+0

很高興知道它幫助你^ _ ^ – EZFrag

0

試試這個,這是很好的ü

private static String sendRequestPost(String url, Object obj) { 
     try { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 

      HttpPost httpost = new HttpPost(url); 
      if (obj != null) { 
       httpost.setEntity(new StringEntity(new Gson().toJson(obj), "utf-8")); 
       System.out.println("Request Json => " + new Gson().toJson(obj)); 
      } 
      httpost.setHeader("Accept", "application/json"); 
      httpost.setHeader("Content-type", "application/json; charset=utf8"); 

      HttpResponse response = httpClient.execute(httpost); 

      HttpEntity responseEntity = response.getEntity(); 
      String strResponse = EntityUtils.toString(responseEntity); 
      return strResponse; 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
      return e.toString(); 
     } 

    }