2015-10-07 260 views
1

下面是我试图复制的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()行的代码。我是否认证错误?

+0

不知道这是否重要,但你的网址是不同的。 – Henry

+0

你有没有尝试'connection.setDoOutput(true);'?获取请求不允许输出。 – Henry

+0

1)cURL请求是一个'POST'请求​​。任何使用'-d'的请求都会隐式成为'POST'。 2)数据应该作为url编码的表单参数发送到请求的主体中,而不是在请求属性中。 3)'Content-Type'头部隐式设置在'application/x-www-form-urlencoded'的cURL请求中。您应该在Java代码中执行相同的操作。 –

回答

1
connection.setRequestMethod("GET"); 

在这里,我们设置方法“GET”,这是因为你用curl使用的相同。

connection.setDoOutput(true); 

在这里,你是隐式设置为“POST”,这是不一样的,所以你没有任何理由期待同样的结果。

不要手工完成所有的认证。使用java.net.Authenticator.这就是它的用途。

1

401 error因为关闭用户身份验证。可能是您的没有正确编码身份验证标头。使用此代码,它的工作对me.you可以得到这里详细here

URL url = new URL ("http://localhost:8080/foo"); 
String encoding = org.apache.catalina.util.Base64.encode(credentials.getBytes("UTF-8")); 

URLConnection uc = url.openConnection(); 
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));