cURL 和 HttpURLConnection - 发布 JSON 数据 [英] cURL and HttpURLConnection - Post JSON Data

查看:22
本文介绍了cURL 和 HttpURLConnection - 发布 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to post JSON data using HttpURLConnection? I am trying this:

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 行收到编译错误.

I am getting compilation error in line 14.

cURL 请求是:

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

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

Is this the way to handle cURL request? Any information will be very helpful to me.

谢谢.

推荐答案

OutputStream 期望使用字节,而您向它传递字符.试试这个:

OutputStream expects to work with bytes, and you're passing it characters. Try this:

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();

这篇关于cURL 和 HttpURLConnection - 发布 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆