小编典典

cURL和HttpURLConnection-发布JSON数据

json

如何使用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请求的方法吗?任何信息对我都会非常有帮助。

谢谢。


阅读 330

收藏
2020-07-27

共1个答案

小编典典

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();
2020-07-27