Skip to content Skip to sidebar Skip to footer

How To Add Parameters To Httprequest In Order To Work With Twitter Api 1.1

I'm working on a project (use twitter api to search for a specific HashTag) when going into this site https://api.twitter.com/1.1/search/tweets.json?q=liverpool&count=20 to get

Solution 1:

If you want to do only timeline searches, the Application-only authentication (https://dev.twitter.com/oauth/application-only) should be fine for you. So as a first step, register a new twitter application. https://apps.twitter.com/

You will need a bearer token:

publicclassTwitterAuthorizationextendsAsyncTask<String, Void, Void> {
String returnEntry;
boolean finished;

privatestaticfinalStringCONSUMER_KEY="yourKey";
privatestaticfinalStringCONSUMER_SECRET="yourSecret";
publicstatic String bearerToken;
publicstatic String tokenType;

privatestaticfinalStringtokenUrl="https://api.twitter.com/oauth2/token";

publicvoidsendPostRequestToGetBearerToken() {
    URLloc=null;
    HttpsURLConnectionconn=null;
    InputStreamReader is;
    BufferedReader in;

    try {
        loc = newURL(tokenUrl);
    }
    catch (MalformedURLException ex) {
        return;
    }

    try {

        StringurlApiKey= URLEncoder.encode(CONSUMER_KEY, "UTF-8");
        StringurlApiSecret= URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
        Stringcombined= urlApiKey + ":" + urlApiSecret;
        byte[] data = combined.getBytes();
        Stringbase64= Base64.encodeToString(data, Base64.NO_WRAP);

        conn = (HttpsURLConnection)loc.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Host", "api.twitter.com");
        conn.setRequestProperty("User-Agent", "1");
        conn.setRequestProperty("Authorization", "Basic " + base64);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestProperty("Content-Length", "29");
        conn.setUseCaches(false);
        StringurlParameters="grant_type=client_credentials";

        DataOutputStreamwr=newDataOutputStream(conn.getOutputStream());
        wr.writeBytes(urlParameters);

        wr.flush();
        wr.close();

        is = newInputStreamReader (conn.getInputStream(), "UTF-8");
        in = newBufferedReader (is);

        readResponse (in);

        setJSONresults();
    }
    catch (IOException ex) {

    }
    finally {
        conn.disconnect();

    }

}


publicvoidreadResponse(BufferedReader in) {
    Stringtmp="";
    StringBufferresponse=newStringBuffer();

    do {
        try {
            tmp = in.readLine();
        }
        catch (IOException ex) {

        }
        if (tmp != null) {
            response.append(tmp);
        }
    } while (tmp != null);
    returnEntry = response.toString();
}

publicvoidsetJSONresults(){
    try {
        JSONObjectobj1=newJSONObject(returnEntry);
        bearerToken =obj1.getString("access_token");
        myLog += bearerToken;

        tokenType = obj1.getString("token_type");
        myLog += tokenType;
    } catch (JSONException ex){

    }
}

@OverrideprotectedvoidonPostExecute(Void result) {
    finished = true;
}

@Overrideprotected Void doInBackground(String... params) {
    finished = false;
    if (bearerToken == null) {
        sendPostRequestToGetBearerToken();
    }
    returnnull;
}

}

Then you can run the queries with your token:

privateStringfetchTimelineTweet(String endPointUrl) throws IOException, ParseException {
    HttpsURLConnection connection = null;
    BufferedReader bufferedReader = null;
    String testUrl = " https://api.twitter.com/1.1/search/tweets.json?q=&geocode=-22.912214,-43.230182,1km&lang=pt&result_type=recent&count=3";
    try {

        URL url = newURL(testUrl);
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        JSONObject jsonObjectDocument = newJSONObject(twitterAuthorizationData);
        String token = jsonObjectDocument.getString("token_type") + " "
                + jsonObjectDocument.getString("access_token");
        connection.setRequestProperty("Authorization", token);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("Accept-Encoding", "identity");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.connect();
        bufferedReader = newBufferedReader(newInputStreamReader(
                connection.getInputStream()));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }

        setJSONObjectResults();

    } catch (MalformedURLException e) {
        thrownewIOException("Invalid endpoint URL specified.", e);
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    returnnewString();
}

publicvoidsetJSONObjectResults(){
    try {
        JSONObject obj = newJSONObject(response.toString());
        JSONArray statuses;
        statuses = obj.getJSONArray("statuses");
        for (int i=0; i < statuses.length(); i++){
            String text = statuses.getJSONObject(i).getString("text");
        }

    } catch (JSONException e) {
        e.printStackTrace();
        myLog += e.toString();
    }

}

You can also have a look over here, but I found it a bit of outdated. android: how to get trends from twitter?

Post a Comment for "How To Add Parameters To Httprequest In Order To Work With Twitter Api 1.1"