gpt4 book ai didi

java - 如何使内容类型为 : application/json in the apache httpPost method

转载 作者:行者123 更新时间:2023-12-05 00:41:56 30 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to send POST request in JSON using HTTPClient in Android?

(5 个回答)


6年前关闭。




我正在使用以下代码,它显示了 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","myEmail@test.com"));
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();
}

最佳答案

在请求的 header 内设置内容类型....

post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");

您也可以从 this answer 看到相同的讨论

关于java - 如何使内容类型为 : application/json in the apache httpPost method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647936/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com