在twitter api请求中获取响应代码401消息

时间:2016-05-05 06:42:42

标签: android twitter

以下代码获取响应代码401.请帮助任何人从twitter api获取搜索推文。我使用http urlconnection而不是httprequest.I需要使用jsonobject获取响应推文

HttpURLConnection urlConnection=null;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.twitterlayout);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        twitter_consumer_key= "";
        twitter_consumer_secret="";
        oauth_token = "";
        oauth_token_secret = "";
        q="India";
        String get_or_post = "GET";
        // This is the signature method used for all Twitter API calls
        String oauth_signature_method = "HMAC-SHA1";
        // generate any fairly random alphanumeric string as the "nonce". Nonce = Number used ONCE.
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts/1000)).toString(); // then divide by 1000 to get seconds
        // assemble the proper parameter string, which must be in alphabetical order, using your consumer key

        String parameter_string = "lang=en&oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method +
                "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + URLEncoder.encode(oauth_token) + "&oauth_version=1.0&q=" + URLEncoder.encode(q) + "&result_type=mixed";`enter code here`
    enter code here

        Log.d("parameter_string=",parameter_string);
        twitter_endpoint = "https://api.twitter.com/1.1/users/search.json";
        twitter_url="https://api.twitter.com/1.1/users/search.json?q=india";

        String signature_base_string = get_or_post + "&"+ URLEncoder.encode(twitter_endpoint) + "&" + URLEncoder.encode(parameter_string);
        String oauth_signature = "";
        try {
            oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
        }
        catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp +
                "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + URLEncoder.encode(oauth_signature) + "\",oauth_token=\"" + URLEncoder.encode(oauth_token) + "\"";
        Log.d("Header String",authorization_header_string);

        URL url = null;       
        try
        {
            Log.d("Url",twitter_url);
            url = new URL(twitter_url);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Host", "api.twitter.com");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
            urlConnection.setRequestProperty("Authorization",authorization_header_string);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setUseCaches(false);
            int responseCode = urlConnection.getResponseCode();
            Log.d("Response Code :", String.valueOf(responseCode));
            InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
            StringBuilder builder = new StringBuilder();
            String responsedata = null;
            while ((inputString = bufferedReader.readLine()) != null) {
                builder.append(inputString);
            }

           JSONObject topLevel = new JSONObject(jsonCallbackToJson(builder.toString()));
            Log.d("Toplevel", builder.toString());
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("URL-ERROR:",e.toString());
        }
        catch (IOException | JSONException e)
        {
            e.printStackTrace();
            Log.i("IO-ERROR:", e.toString());
        }
}

1 个答案:

答案 0 :(得分:0)

401表示您已通过身份验证破坏了某些内容

然而,不要重新发明轮子。

您可以使用TwitterCore Kit处理身份验证,并且易于使用工具以满足您的需求。它提供了一个TwitterApiClient来进行经过身份验证的Twitter API请求。