下面是我试图复制的curl命令:HttpUrlConnection身份验证不起作用
下面是curl请求。
curl user:[email protected]: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();
在我得到一个401错误connection.getInputStream()行的代码。我是否认证错误?
不知道这是否重要,但你的网址是不同的。 – Henry
你有没有尝试'connection.setDoOutput(true);'?获取请求不允许输出。 – Henry
1)cURL请求是一个'POST'请求。任何使用'-d'的请求都会隐式成为'POST'。 2)数据应该作为url编码的表单参数发送到请求的主体中,而不是在请求属性中。 3)'Content-Type'头部隐式设置在'application/x-www-form-urlencoded'的cURL请求中。您应该在Java代码中执行相同的操作。 –