Application Only Authentication - Error Code 86 “This method requires a GET or HEAD”

android
oauth

#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 on from command prompt and it worked perfect.

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'

Please help me. Its getting very frustrating


#2

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.


#3

Hi @Kaidul - Since you were able to resolve this, I’m closing this thread.

Thanks for being a community member and using the forums!

Best,
Kevin


#4