如何设置HttpsURLConnection的Authentication Header

时间:2014-09-05 17:56:59

标签: java

我需要设置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执行相同的请求,这在那里工作正常。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

Oauth签名似乎缺少所需的最终URL编码-我认为。应以3D结尾,并以等号编码。