gpt4 book ai didi

java - cURL 和 HttpURLConnection - 发布 JSON 数据

转载 作者:太空狗 更新时间:2023-10-29 22:31:53 25 4
gpt4 key购买 nike

如何使用 HttpURLConnection 发布 JSON 数据?我正在尝试这个:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

StringReader reader = new StringReader("{'value': 7.5}");
OutputStream os = httpcon.getOutputStream();

char[] buffer = new char[4096];
int bytes_read;
while((bytes_read = reader.read(buffer)) != -1) {
os.write(buffer, 0, bytes_read);// I am getting compilation error here
}
os.close();

我在第 14 行遇到编译错误。

cURL 请求是:

curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "{'value': 7.5}" \
"a URL"

这是处理 cURL 请求的方式吗?任何信息都会对我很有帮助。

谢谢。

最佳答案

OutputStream 期望处理字节,而您正在向它传递字符。试试这个:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

os.close();

关于java - cURL 和 HttpURLConnection - 发布 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9623158/

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