【发布时间】:2015-10-07 04:03:56
【问题描述】:
这是我尝试复制的 curl 命令:
以下是 curl 请求。
curl user:password@localhost:8080/foo/bar -d property_one=value_one -d property_two=value_two -d property_three=value_three
这里是httpurlconnection的代码
URL thisurl = new URL ("http://localhost:8080/foo");
String encoding = Base64Encoder.base64Encode("user:password");
HttpURLConnection connection = (HttpURLConnection) thisurl.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.addRequestProperty("property_one", "value_one");
connection.addRequestProperty("property_two", "value_two");
connection.addRequestProperty("property_three", "property_three");
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
在 connection.getInputStream() 行我收到 401 错误。我是不是做错了身份验证?
【问题讨论】:
-
不知道这是否重要,但您的网址不同。
-
你试过没有
connection.setDoOutput(true);吗?获取请求不允许输出。 -
1) cURL 请求是一个
POST请求。任何带有-d的请求都将隐含地生成POST。 2) 数据应该在请求正文中作为 url 编码的表单参数发送,而不是在请求属性中。 3)Content-Type标头在 cURL 请求中隐式设置为application/x-www-form-urlencoded。你应该在 Java 代码中做同样的事情。
标签: java curl httpurlconnection