【问题标题】:curl to request in javacurl在java中请求
【发布时间】:2016-03-07 12:57:03
【问题描述】:

我必须向 api 发出请求。 有效的卷曲是:

curl -u apiKey:pass -H "Accept: application/json" https://subdomain.chargify.com/portal/customers/id/management_link.json

我目前的java代码是:

String userpass = apiKey + ":" + pass;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));

URL url = new URL(stringUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestProperty("Accept", "application/json");
uc.setRequestProperty("Authorization", basicAuth);

InputStream content = uc.getInputStream();
int status = uc.getResponseCode();
BufferedReader in = new BufferedReader (new InputStreamReader(content));

String line;
while ((line = in.readLine()) != null) {
        System.out.println(line);
}

每次我收到 401 响应代码。 我做错了什么?

【问题讨论】:

    标签: java httpurlconnection urlconnection


    【解决方案1】:

    您的请求需要用户身份验证。由于请求已包含授权凭证,因此 401 响应表明已拒绝对这些凭证进行授权。检查您如何生成和验证密钥

    【讨论】:

    • 你是对的。凭证形式是 apiKey:x 其中 x 是密码。我将 api 密钥保存在应用程序属性文件中,如“apikey”,当我使用它时,它变成了“apikey”。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    相关资源
    最近更新 更多