简体   繁体   中英

Send GET request with token using Java HttpUrlConnection

I have to work with RESTful web service which uses token-based authentication from Java application. I can successfully get token by this way:

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

But I cannot find a way to properly send this token in the get request. What I'm trying:

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

doesn't work. Any help to solve this problem will be highly appreciated.

You should add the token to request url:

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

As an alternative, use restTemplate to send a get request:

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

Solved. Server returns some extra strings besides token. All I had to do is to extract pure token from the received answer and paste it without any encoding: String authString = "Bearer " + pure_token;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM