如何将参数添加到httprequest以使用twitter api 1.1

时间:2017-04-10 11:35:16

标签: android api authentication httpurlconnection twitter-oauth

我正在处理一个项目(使用twitter api搜索特定的HashTag) 进入此网站virtual以获得回复

ev

之后我知道我应该注册我的应用程序以获取消费者密钥,消费者密钥,访问令牌,访问令牌秘密但我不知道如何将此令牌添加到我的Android代码中以便 这是我的makehttpconnection方法,我想将此标记添加到连接

{"errors":[{"code":215,"message":"Bad Authentication data."}]}

注意:我无法使用Twitter sdk

1 个答案:

答案 0 :(得分:1)

如果您只想进行时间线搜索,那么仅限应用程序的身份验证(https://dev.twitter.com/oauth/application-only)应该没问题。 因此,作为第一步,注册一个新的Twitter应用程序。 https://apps.twitter.com/

您将需要持票人令牌:

public class TwitterAuthorization extends AsyncTask<String, Void, Void> {
String returnEntry;
boolean finished;

private static final String CONSUMER_KEY = "yourKey";
private static final String CONSUMER_SECRET = "yourSecret";
public static String bearerToken;
public static String tokenType;

private static final String tokenUrl = "https://api.twitter.com/oauth2/token";

public void sendPostRequestToGetBearerToken () {
    URL loc = null;
    HttpsURLConnection conn = null;
    InputStreamReader is;
    BufferedReader in;

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

    try {

        String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
        String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
        String combined = urlApiKey + ":" + urlApiSecret;
        byte[] data = combined.getBytes();
        String base64 = 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);
        String urlParameters = "grant_type=client_credentials";

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(urlParameters);

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

        is = new InputStreamReader (conn.getInputStream(), "UTF-8");
        in = new BufferedReader (is);

        readResponse (in);

        setJSONresults();
    }
    catch (IOException ex) {

    }
    finally {
        conn.disconnect();

    }

}


public void readResponse(BufferedReader in) {
    String tmp = "";
    StringBuffer response = new StringBuffer();

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

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

public void setJSONresults(){
    try {
        JSONObject obj1 = new JSONObject(returnEntry);
        bearerToken =obj1.getString("access_token");
        myLog += bearerToken;

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

    }
}

@Override
protected void onPostExecute(Void result) {
    finished = true;
}

@Override
protected Void doInBackground(String... params) {
    finished = false;
    if (bearerToken == null) {
        sendPostRequestToGetBearerToken();
    }
    return null;
}

}

然后,您可以使用令牌运行查询:

private String fetchTimelineTweet(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 = new URL(testUrl);
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        JSONObject jsonObjectDocument = new JSONObject(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 = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

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

        setJSONObjectResults();

    } catch (MalformedURLException e) {
        throw new IOException("Invalid endpoint URL specified.", e);
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return new String();
}

public void setJSONObjectResults(){
    try {
        JSONObject obj = new JSONObject(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();
    }

}

你也可以看看这里,但我发现它有点过时了。 android: how to get trends from twitter?