简体   繁体   中英

How to send Bearer token with request

I'm attempting to use the Twitter API to return a List of tweets and following this tutorial to invoke a GET request with parameters: https://www.baeldung.com/java-http-request

Here is my code based off tutorial:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class GetTweets {

    public static void main(String argsp[]) throws IOException {
        URL url = new URL("https://api.twitter.com/2/users/1315617658461659136/tweets");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        Map<String, String> parameters = new HashMap<>();
        parameters.put("Token", "******");
        con.setDoOutput(true);
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();

        System.out.println("Response is "+content);
    }
}

returns:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL: https://api.twitter.com/2/users/1315617658461659136/tweets
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
    at com.reactive.api.twitter.GetTweets.main(GetTweets.java:27)

If I use Postman and set the Bearer token in the Authorization tab the tweets are returned correctly:

在此处输入图像描述

So it seems I'm not passing the Bearer token parameter correctly?

How to pass the Bearer token with the Get request?

The bearer goes in the "Authorization" header:

con.setRequestProperty("Authorization", "Bearer " + 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