2012-01-23 54 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(); 
     } 

    }