1

I am trying to fetch tweets for https://api.twitter.com/1.1/search/tweets.json?q=nasa&count=5 using application only bearer token which I got using consumer key and consumer secret successfully. But I am not able to fetch the tweets. This is my code:

public class SearchTweetsTask extends AsyncTask<String, Void, String> {

    private static final String TWITTER_HOST = "api.twitter.com";
    private static final String TWITTER_USER_AGENT = "TwitterMotion User Agent";

    private Logger logger = Logger.getLogger();

    @Override
    protected String doInBackground(String... tokens) {
        String endPointUrl = tokens[0];
        HttpsURLConnection urlConnection = null;

        try {
            urlConnection = getHTTPSConnection("GET", endPointUrl);
            urlConnection.setRequestProperty("Authorization",
                    "Bearer " + APPLICATION_ONLY_BEARER_TOKEN);


            String jsonResponse = readResponse(urlConnection);

            return responseAsJsonObject.toString();
        }
        catch (Exception ex) {
            logger.e(ex);
            return null;
        }
        finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    @Override
    protected void onPostExecute(String asyncTaskResult) {
        logger.i(asyncTaskResult);
    }



    public static HttpsURLConnection getHTTPSConnection(String requestMethod, String endpointUrl)
            throws IOException {
        URL url = new URL(endpointUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod(requestMethod);
        connection.setRequestProperty("Host", TWITTER_HOST);
        connection.setRequestProperty("User-Agent", TWITTER_USER_AGENT);
        connection.setUseCaches(false);
        return connection;
    }


    public static String readResponse(HttpsURLConnection connection) throws IOException {
        BufferedReader bufferedReader = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + System.getProperty("line.separator"));
            }
            return stringBuilder.toString();
        }
        catch (IOException ex) {
            throw ex;
        }
        finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    }
}

Inside readRequest() method, the connection object is not working as expected. I checked connection.getResponseCode() and its returning 400 and connection.getErrorStream() is returning Error Code 86 “This method requires a GET or HEAD”.

I tried with cURL from command line and it worked perfectly.

curl -X GET \
  'https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular' \
  -H 'Authorization: Bearer <Application Only Bearer Token>' \
  -H 'Cache-Control: no-cache' \
  -H 'Host: api.twitter.com' \
  -H 'User-Agent: TwitterMotion User Agent'

Its getting very frustrating. Thanks in advance!

Kaidul
  • 15,409
  • 15
  • 81
  • 150

1 Answers1

1

As stated here, the httpCon.setDoOutput(true) implicitly set the request method to POST because that's the default method whenever you want to send a request body.

If you want to use GET, remove that line.

Kaidul
  • 15,409
  • 15
  • 81
  • 150