服务器在从twitter获取推文时返回HTTP响应代码:400用于URL

时间:2016-01-27 07:10:08

标签: java twitter oauth http-status-code-400

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


    public class Twitter{
    public static String getTwitterBearerTokenUrl() 
    {
        return "https://api.twitter.com/oauth2/token";
    }

    public static void main(String[] args) throws IOException {

    final Logger logger = LoggerFactory.getLogger("Twitter");

    String base64Key  = null; 

    String Authorization = "Authorization";
    String BEARER = "Bearer";
    String UTF_CHARSET = "UTF-8";

    logger.info("Twitter::getBearerToken --> In");
    String AccessToken = null;
    StringBuffer buffer = new StringBuffer(); 

    base64Key = DatatypeConverter
                .printBase64Binary(("Customer_id"+":"+"Customer_secret")
                        .getBytes());
    logger.debug("base64Key: " +base64Key);

    URL twitterBearerTokenUrl;

    try {
            twitterBearerTokenUrl = new URL(getTwitterBearerTokenUrl());

        }catch (MalformedURLException e) {
            e.printStackTrace();
            logger.error("Invalid Request  " + e);
            throw new RuntimeException("Invalid Request  " + e);
        }

    HttpURLConnection urlConnection;
    try{
    urlConnection=       (HttpURLConnection)twitterBearerTokenUrl.openConnection();

    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty(Authorization ,"Basic "+ base64Key);
    urlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset="
                            + UTF_CHARSET);

    urlConnection.setDoOutput(true);

    DataOutputStream wr = new DataOutputStream(
                    urlConnection.getOutputStream());

    wr.writeBytes("grant_type=client_credentials");
    wr.flush();
    wr.close();

    InputStream inputstr =  urlConnection.getInputStream();
    InputStreamReader ireader = new InputStreamReader(inputstr);
    BufferedReader Reader1 =  new BufferedReader(ireader);

    String read;

    while ((read = Reader1.readLine()) != null) {

    System.out.println(read);
    buffer.append(read);
    }


        }catch (Exception e) {
            e.printStackTrace();
            logger.error("Unable to connect with Twitter " + e);
            throw new RuntimeException("Unable to connect with Twitter " + e);
        }
        AccessToken = buffer.toString();

        String[] tokens = AccessToken.split(",");

        for (String token : tokens) {
            String[] parts = token.split(":");
            if (parts.length != 2) {
                throw new RuntimeException("Unexpected auth response");
            } else {
                if (parts[0].equals("\"access_token\"")) {
                    parts[1] = parts[1].replace("\"", "");
                    parts[1] = parts[1].replace("}", "");
                    AccessToken = parts[1];
                    break;
                }
            }
        }

        logger.debug("accessToken: "+ AccessToken);
        logger.info("Twitter::getBearerToken --> Out");


        System.out.println("\nAccess token is : ----------> " + AccessToken+ "\n");
        String username ="SrBachchan";
        int count = 10;

        ArrayList<String> tweets = new ArrayList<String>();

        HttpsURLConnection getUrlConnection;
        getUrlConnection = null;
        URL geturl = null;      
        String url2 = null;

               url2 = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name="
                        + username +"&" + "count="+count;

                //url2 = url2.substring(0, (url2.length()-1));
                System.out.println("\nURL2 is :--->" + url2+"\n");
        try {

             geturl = new URL(url2);

        } catch (MalformedURLException e) {
            e.printStackTrace();
            logger.error("Invalid Request  " + e);
            throw new RuntimeException("Invalid Request  " + e);
        }
        try {
            getUrlConnection = (HttpsURLConnection)geturl.openConnection();

            getUrlConnection.setRequestMethod("GET");
            getUrlConnection.setRequestProperty(Authorization, BEARER
                    + AccessToken);

            getUrlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset="
                            + UTF_CHARSET);

            getUrlConnection.setDoOutput(true);

        } catch (Exception e) {

            e.printStackTrace();

            throw new RuntimeException("Unable to request the process ");
        }
        DataOutputStream wr1 = new DataOutputStream(
                getUrlConnection.getOutputStream());

        wr1.writeBytes("grant_type=client_credentials");
        wr1.flush();
        wr1.close();

        System.out.println("*****************Before buffer*****************");
        BufferedReader reader;




        try {

            reader = new BufferedReader(new InputStreamReader(
                    getUrlConnection.getInputStream()));
            String read;
            while ((read = reader.readLine()) != null) {
                        buffer.append(read);
            }
             System.out.println(buffer.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

这里的错误:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=SrBachchan&count=10
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.aricent.oauth.Twitter.main(Twitter.java:206)

上下文:   我试图使用从代码中获取的访问令牌从twitter获取特定用户的推文,但它抛出一些https:错误的请求400.我无法理解它,因为我正在接收Access令牌但是当我我正在使用它来获取推文然后它会抛出错误的请求异常。

0 个答案:

没有答案