Get 请求中的奇怪行为

Strange behaviour in Get request

注意:这包含固定代码。

以下获取请求有效:

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

但是 java 中的以下代码我虽然做了相同的 returns 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);

我在这里错过了什么? 那些不一样吗?

401表示未授权。没什么好惊讶的。问题是 curl 能够解析 URL 中使用的 username:password('@' 符号之前的部分)并自动将其附加为 Authorization header 在您的请求中。但是 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 基本授权 header 附加到您的请求中。所以正确的 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 中使用凭据并仅使用授权 header(请求 属性)。顺便说一句,如果你解码 Base64:OWQzZDk5MzQ2MDlkMWE3ZDc5ODY1MjMxYmUxZWNiMjM6OTQzMmZiNzZhMzRhMGQ0NmQ2NGEyZjRjZjgxYmViZDY=,你将得到 '@' 之前 URL 的确切部分,即:9d3d9934609d1a7d79865231be1ecb23:9432fb76a34a0d46d64a2f4cf81bebd6

如果您想要自动解决您的授权问题header,您可以使用

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

401错误代表未授权访问。

您需要使用身份验证器:

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