使用Java HttpUrlConnection发送带有令牌的GET请求

4

我需要在Java应用程序中使用基于令牌的身份验证与RESTful web服务进行交互。通过以下方式,我可以成功获取令牌:

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

public void getHttpCon() throws Exception{

String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
URL obj = new URL("http://someIP/oauth/token");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
        "Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
        "application/x-www-form-urlencoded");

// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END

int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) { //success
    BufferedReader in = new BufferedReader(new InputStreamReader(
            con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // print result
    System.out.println(response.toString());
} else {
    System.out.println("POST request not worked");
}
}    

但是我找不到合适的方法在get请求中正确发送这个令牌。我的尝试:

    public StringBuffer getSmth(String urlGet, StringBuffer token) throws IOException{

    StringBuffer response = null;
    URL obj = new URL(urlGet);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");

    String authString = "Bearer " + Base64.getEncoder().withoutPadding().encodeToString(token.toString().getBytes("utf-8"));
    con.setRequestProperty("Authorization", authString);

    int responseCode = con.getResponseCode();
    System.out.println("GET Response Code :: " + responseCode);
    if (responseCode == HttpURLConnection.HTTP_OK) { // success
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    } else {
        System.out.println("GET request not worked");
    }
    return response;
}

不起作用。希望能得到帮助解决这个问题,非常感谢。

2个回答

2

问题已解决。服务器返回了除令牌本身之外的一些额外字符串。我所要做的就是从接收到的答案中提取纯令牌,并将其粘贴而不进行任何编码:String authString = "Bearer " + pure_token;


1
您应该将令牌添加到请求URL中:

String param = "?Authorization=" + token;
URL obj = new URL(urlGet + param);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");

作为替代方案,使用restTemplate发送GET请求:
RestTemplate restTemplate = new RestTemplate();  
HttpHeaders headers = new HttpHeaders();  
headers.add("Authorization", "Basic " + token);
HttpEntity<String> request = new HttpEntity<String>(headers);  
ResponseEntity<String> response = restTemplate.exchange(urlGet, HttpMethod.GET,  request, String.class);

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