[英]Java: Preview HttpPost Request
I am trying to send JSON formatted data to a server using Java. 我正在尝试使用Java将JSON格式的数据发送到服务器。 The information is getting to the server, but the server is responding with a "Bad Request".
信息到达服务器,但服务器正在响应“错误请求”。
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);
That is the basic setup of my request. 这是我的请求的基本设置。 Here is the JSONData:
这是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}}
If this looks right to you lot, I'll start spamming the admins, but for now, I need to know if I am missing something. 如果这对你来说很合适,我会开始向管理员发送垃圾邮件,但是现在,我需要知道我是否遗漏了一些东西。
I found the issue... The server is extremely sensitive to the content type header and the content format 我发现了这个问题......服务器对内容类型标题和内容格式非常敏感
httpost.setHeader("Content-type", "application/json;charset=utf8");
Needed to be changed to 需要改为
httpost.setHeader("Content-type", "application/json; charset=utf-8");
and StringEntity se = new StringEntity(JSONRequest); 和StringEntity se = new StringEntity(JSONRequest);
needed to be changed to 需要改为
StringEntity se = new StringEntity(JSONRequest,"utf-8");
Thanks Jens, that one comment pushed me into the right direction. 谢谢Jens,一条评论将我推向了正确的方向。
Try this one, it's good for u 试试这个,这对你有好处
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.