HttpClient中的Bearer令牌授权?

40

我正在尝试使用Java访问API并使用oauth2授权令牌。以下是客户端代码:

DefaultHttpClient httpclient = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://res-api");
post.setHeader("Content-Type","application/json");
post.setHeader("Authorization", "Bearer " + finalToken);

JSONObject json = new JSONObject();
// json.put ...
// Send it as request body in the post request 

StringEntity params = new StringEntity(json.toString());
post.setEntity(params);

HttpResponse response = httpclient.execute(post);
httpclient.getConnectionManager().shutdown();

这将返回401错误。

使用相同的令牌,等效的curl命令没有任何问题:

curl -H "Content-Type:application/json" -H "Authorization:Bearer randomToken" -X POST -d @example.json http://rest-api

我尝试注销该请求,并且看起来授权设置正确

DEBUG [2016-06-28 20:51:13,655] org.apache.http.headers: >> Authorization: Bearer authRandomToKen; Path=/; Domain=oauth2-server; Expires=Wed, 29 Jun 2016 20:51:13 UTC

我通过复制粘贴相同的令牌尝试了curl命令,它正常工作。

虽然我也看到了这行字

DEBUG [2016-06-28 20:51:13,658] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges

谢谢你的指点,我已经按照建议修改了问题。没有运气。 - user_mda
响应头是否也应包含身份验证令牌?我刚试着记录它,但没有记录到。 - user_mda
使用 Fiddler 检查出站请求。 - Legends
这个重要问题有任何新进展吗? - tm1701
我建议使用Chrome浏览器的扩展程序Boomerang来测试。我每天在工作中都是使用它来解决完全相同的问题。 - Dom
显示剩余4条评论
3个回答

35

我曾经遇到过类似的情况,我通过以下方式解决了它,希望这能帮助其他人。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {


    public static void main(String[] args) throws Exception {

        // Sending get request
        URL url = new URL("http://example-url");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestProperty("Authorization","Bearer "+" Actual bearer token issued by provider.");
        //e.g. bearer token= eyJhbGciOiXXXzUxMiJ9.eyJzdWIiOiPyc2hhcm1hQHBsdW1zbGljZS5jb206OjE6OjkwIiwiZXhwIjoxNTM3MzQyNTIxLCJpYXQiOjE1MzY3Mzc3MjF9.O33zP2l_0eDNfcqSQz29jUGJC-_THYsXllrmkFnk85dNRbAw66dyEKBP5dVcFUuNTA8zhA83kk3Y41_qZYx43T

        conn.setRequestProperty("Content-Type","application/json");
        conn.setRequestMethod("GET");


        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String output;

        StringBuffer response = new StringBuffer();
        while ((output = in.readLine()) != null) {
            response.append(output);
        }

        in.close();
        // printing result from response
        System.out.println("Response:-" + response.toString());

    }
}

1
以上的代码运行正常。但是Eclipse想让我在它周围加上try/catch。 - Will Buffington

26

我曾试图使用HttpClient做类似的事情,最终通过以下小改动实现了它。

post.setHeader(HttpHeaders.CONTENT_TYPE,"application/json");
post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + finalToken);

3
I have implemented above given code for receiving Pipedream SSE real time events.Below The Below Code is working fine in Eclipse WITHOUT a 401 ERROR.

package //////YOUR PACKAGE NAME HERE/////

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class HttpURLConnectionExample {


    public static void main(String[] args) throws Exception {

        // Sending get request
        URL url = new URL("https://your Server website");
        
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization","Bearer PLACE.HERE");
        
        //e.g. bearer token= eyJhbGciOiXXXzUxMiJ9.eyJzdWIiOiPyc2hhcm1hQHBsdW1zbGljZS5jb206OjE6OjkwIiwiZXhwIjoxNTM3MzQyNTIxLCJpYXQiOjE1MzY3Mzc3MjF9.O33zP2l_0eDNfcqSQz29jUGJC-_THYsXllrmkFnk85dNRbAw66dyEKBP5dVcFUuNTA8zhA83kk3Y41_qZYx43T

        //conn.setRequestProperty("Content-Type","application/json");
        
       conn.setRequestMethod("GET");
        
       
        
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String output;

        StringBuffer response = new StringBuffer();
       
        
        while ((output = in.readLine()) != null) {
            System.out.println("Response:-" + output.toString());
    ////you will get output in "output.toString()" ,Use it however you like
        }
        in.close();
        
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接