Java 如何在apache httpPost方法中制作content-type:application/json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29647936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make the content-type: application/json in the apache httpPost method
提问by Nikunj Aggarwal
I am using the below code and it is showing the Content-Type:application/x-www-form-urlencoded, but I want this code to be Content-Type: application/json. Please suggest what changes needed to this code to make it an application/json request.
我正在使用以下代码,它显示了 Content-Type:application/x-www-form-urlencoded,但我希望此代码为 Content-Type: application/json。请建议需要对此代码进行哪些更改以使其成为应用程序/json 请求。
private String baseUrl = "myIPAddress";
private HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(baseUrl + "app/registration");
try {
String line = "";
for (int rIndex = 0; rIndex < goodAuthenticationPairs.length; rIndex++) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("email","[email protected]"));
nameValuePairs.add(new BasicNameValuePair("password","myPassword"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//post.setHeader("Content-type", "application/json");
System.out.println(post);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
line = rd.readLine();
System.out.println(line);
JSONObject json = (JSONObject) new JSONParser().parse(line);
String actualResult = json.get("return_code").toString();
assertTrue("0".equals(actualResult));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
回答by Rahul
I think uncommenting the line
我认为取消注释该行
//post.setHeader("Content-type", "application/json");
will solve your problem.
将解决您的问题。
回答by Deepika Rajani
This may serve the need ..
这可能满足需要..
response.setContentType("application/json");
response.setContentType("application/json");
回答by Angad Tiwari
Set the content type inside header of the request....
在请求的标头内设置内容类型....
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
you can also see the same discussion from this answer
你也可以从这个答案中看到同样的讨论