首页 文章

如何设置HttpsURLConnection的Authentication Header

提问于
浏览
0

我需要设置HTTPS GET请求的OAuth身份验证标头,并且要设置的标头如下所示

Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxx" ,oauth_signature_method="HMAC-SHA1" ,oauth_timestamp="1409861973" ,oauth_nonce="x1409861973681" ,oauth_version="1.0" ,oauth_signature="M+Dq62XboEd3+t6VDIcLy86zlQg="

我在下面使用以下java代码

String url = null;
    try {
        url = "https://secure.api.abc.net/data/ServiceAccount?schema=1.0&byBillingAccountId=" + URLEncoder.encode("{EQUALS,acc@xyz.edu}", "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    String header = OAuthClient.prepareURLWithOAuthSignature(url1);

    HttpsURLConnection con = null;

    try {
        URL obj = new URL(url);
        con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("GET");
        con.setRequestProperty("Authorization", header);

        int responseCode = con.getResponseCode();

        System.out.println("Response Code = " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        con.disconnect();
        //print result
        System.out.println("Response = " + response.toString());


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(con!=null) con.disconnect();
    }

似乎con.setRequestProperty(“Authorization”,header)没有设置Authorization标头,因此服务器返回401 .

知道如何解决这个问题 .

注意:我试图从POSTMAN执行相同的请求,这在那里工作正常 .

1 回答

  • 0

    您以正确的方式添加标头,似乎您不知道401错误是由丢失的 Authorization 标头还是标头中的错误值引起的 .

    您应该尝试将您的请求发送到myhttp.infowhatismybrowser等网站,该网站将返回您请求中的所有标头 . 只需在标准输出上打印它们,这样您就可以确定是否发送了 Headers .

相关问题