【问题标题】:How to add parameters to httprequest in order to work with twitter api 1.1如何向 httprequest 添加参数以使用 twitter api 1.1
【发布时间】:2017-04-10 11:35:16
【问题描述】:

我正在做一个项目(使用 twitter api 搜索特定的 HashTag) 当进入这个网站https://api.twitter.com/1.1/search/tweets.json?q=liverpool&count=20得到回复时

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

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

private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

注意:我无法使用 Twitter sdk

【问题讨论】:

    标签: android api authentication httpurlconnection twitter-oauth


    【解决方案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?

    【讨论】:

    • 谢谢,它起作用了,但我有点困惑:在方法 sendPostRequestToGetBearerToken() 的代码中,我们使用 conn.setRequestMethod("POST");但是当我调试代码时,我发现该方法自动转换为“GET”。我还有一个关于 conn.setDoInput(true); 的问题。 conn.setDoOutput(true);这两种方法到底是做什么的?
    • 我真的不知道你问题第一部分的答案,但如果有人知道我很想听听。根据文档: HttpURLConnection.setDoOutput:“可选择上传请求正文。如果实例包含请求正文,则必须使用 setDoOutput(true) 进行配置。” HttpURLConnection.setDoInput:HttpURLConnection 默认使用 GET 方法。如果 setDoOutput(true) 已被调用,它将使用 POST。 https://developer.android.com/reference/java/net/HttpURLConnection.html希望有帮助
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 2023-03-09
    • 1970-01-01
    • 2013-06-09
    • 2013-06-11
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多