gpt4 book ai didi

java - 如何在HTTP中传递JSON正文放在JAVA中

转载 作者:行者123 更新时间:2023-12-02 10:27:44 27 4
gpt4 key购买 nike

有人可以解释一下如何在请求正文中传递 JSON 参数吗?我正在使用 HttpURLConnection 创建连接,如下所示:

URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url); //URL is hardcoded as of now
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("cache-control", "no-cache");
con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");

JSONObject reqBody = new JSONObject();
reqBody.put("state", "4");
System.out.println(reqBody);
StringEntity params = new StringEntity(reqBody.toString());
if( reqBody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());

如何在这里设置请求主体?

最佳答案

用于指定请求的正文:

OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()

关于java - 如何在HTTP中传递JSON正文放在JAVA中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803125/

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