Get请求中的奇怪行为

时间:2015-10-12 18:56:31

标签: java shopify

注意:这包含固定代码。

以下获取请求有效:

curl https://9d3d9934609d1a7d79865231be1ecb23:9432fb76a34a0d46d64a2f4cf81bebd6@smartprice-2.myshopify.com/admin/orders.json

但是我在java中的以下代码虽然做了同样的回复,但却返回401.

        final String url = "https://9d3d9934609d1a7d79865231be1ecb23:9432fb76a34a0d46d64a2f4cf81bebd6@smartprice-2.myshopify.com/admin/orders.json";
        final HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/json");
        final String encoded = Base64.encodeBase64String((api+":"+pass).getBytes());
        con.setRequestProperty("Authorization", "Basic "+encoded);

        System.out.println("\nSending 'GET' request to URL : " + url);
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

我在这里缺少什么? 那些不相同吗?

2 个答案:

答案 0 :(得分:3)

401表示未经授权。没什么好惊讶的。问题是curl能够解析您的URL中使用的用户名:密码(在'@'符号之前的部分),并在请求中自动将其作为授权标头附加。但是Java API没有这样做,所以你必须自己做。调查的最佳方法是使用-v选项运行curl。在其中,你会看到类似的东西:

* Server auth using Basic with user '9d3d9934609d1a7d79865231be1ecb23'
> GET /admin/orders.json HTTP/1.1
> Host: smartprice-2.myshopify.com
> Authorization: Basic OWQzZDk5MzQ2MDlkMWE3ZDc5ODY1MjMxYmUxZWNiMjM6OTQzMmZiNzZhMzRhMGQ0NmQ2NGEyZjRjZjgxYmViZDY=
> User-Agent: curl/7.44.0
> Accept: */*

因此,您可以注意到curl会自动将HTTP基本授权标头附加到您的请求中。所以正确的Java代码是:

final String url = "https://smartprice-2.myshopify.com/admin/orders.json";
final HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
con.setRequestProperty("Authorization", "Basic OWQzZDk5MzQ2MDlkMWE3ZDc5ODY1MjMxYmUxZWNiMjM6OTQzMmZiNzZhMzRhMGQ0NmQ2NGEyZjRjZjgxYmViZDY=");
con.setRequestMethod("GET");
System.out.println("Response Code : " + con.getResponseCode());

您可以注意到,没有理由在URL中使用凭据并仅使用Authorization标头(请求属性)。顺便说一句,如果您解码Base64:OWQzZDk5MzQ2MDlkMWE3ZDc5ODY1MjMxYmUxZWNiMjM6OTQzMmZiNzZhMzRhMGQ0NmQ2NGEyZjRjZjgxYmViZDY=,您将获得“@”之前的URL部分:9d3d9934609d1a7d79865231be1ecb23:9432fb76a34a0d46d64a2f4cf81bebd6

如果您想以自动方式解决授权标题,可以使用

final String credentials = DatatypeConverter.printBase64Binary("username:password".getBytes());
con.setRequestProperty("Authorization", "Basic " + credentials);

答案 1 :(得分:2)

401错误代表未经授权的访问。

您需要使用Authenticator:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});

或设置属性:

String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
相关问题