使用Java HttpUrlConnection

时间:2017-08-17 09:28:53

标签: java get token httpurlconnection access-token

我必须使用RESTful Web服务,该服务使用Java应用程序中基于令牌的身份验证。我可以通过这种方式成功获得令牌:

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 个答案:

答案 0 :(得分:1)

您应该将令牌添加到请求网址:

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

作为替代方案,请使用restTemplate发送获取请求:

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);

答案 1 :(得分:1)

解决。除了令牌,服务器返回一些额外的字我所要做的就是从收到的答案中提取纯粹的令牌并粘贴它而不进行任何编码:String authString =&#34; Bearer&#34; + pure_token;