使用纯Java 400搜索推文得到错误请求

时间:2015-03-27 16:54:17

标签: java twitter twitter-oauth

我尝试使用搜索推文使用twitter搜索api。 但是当我得到持票人令牌然后发送请求  /1.1/search/tweets.json?count=2

它的回复是400(错误请求) 我不知道怎么回事......任何人都可以帮助我?

这是我的代码全部来自http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/

我也看Application-only authentication但仍然不知道为什么。

希望有人能告诉我......

private final static String getTokenURL = "https://api.twitter.com/oauth2/token";   
private static String bearerToken;
 static final String ACCESS_TOKEN = "1111111112-H************************************s";
  static final String ACCESS_SECRET = "S************************************n";
  static final String CONSUMER_KEY = "q************************************g";
  static final String CONSUMER_SECRET = "Q************************************a";



public static void main(String[] args) {

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {

                bearerToken = requestBearerToken(getTokenURL);
                searchTweets("https://api.twitter.com/1.1/search/tweets.json?count=2");

            } catch (IOException e) {
                System.out.println("IOException e");
                e.printStackTrace();
            }
        }
    }).start();

}


private static String encodeKeys(String consumerKey, String consumerSecret) {
    try {
        String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
        String encodedConsumerSecret = URLEncoder.encode(consumerSecret,
                "UTF-8");

        String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
        byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());

        return new String(encodedBytes);
    } catch (UnsupportedEncodingException e) {
        return new String();
    }
}

private static String requestBearerToken(String endPointUrl)
        throws IOException {
    HttpsURLConnection connection = null;
    String encodedCredentials = encodeKeys(CONSUMER_KEY, CONSUMER_SECRET);


    try {
        URL url = new URL(endPointUrl);
        connection = (HttpsURLConnection) url.openConnection();
        System.out.println(connection);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
        connection.setRequestProperty("Authorization", "Basic "
                + encodedCredentials);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        connection.setRequestProperty("Content-Length", "29");
        connection.setUseCaches(false);

        writeRequest(connection, "grant_type=client_credentials");
        System.out.println(connection.getResponseCode());
        System.out.println(connection.getResponseMessage());


        String result = readResponse(connection);

        JSONObject jsonResult=new JSONObject(result);



        if (jsonResult.get("token_type") != null && jsonResult.get("token_type").equals("bearer") ) {
            return jsonResult.getString("access_token");
        }
        return new String();
    } catch (MalformedURLException | JSONException e) {
        throw new IOException("Invalid endpoint URL specified.", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}


private static String searchTweets(String endPointUrl) throws IOException {
    HttpsURLConnection connection = null;

    try {
        URL url = new URL(endPointUrl); 
        connection = (HttpsURLConnection) url.openConnection();           
        connection.setDoOutput(true);
        connection.setDoInput(true); 
        connection.setRequestMethod("GET"); 
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
        connection.setRequestProperty("Authorization", "Bearer " + bearerToken);


        connection.setUseCaches(false);


        String result = readResponse(connection);
        System.out.println("fetchTimelineTweet---result:"+result);

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


// Writes a request to a connection
private static boolean writeRequest(HttpURLConnection connection,
        String textBody) {
    try {
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
                connection.getOutputStream()));
        wr.write(textBody);
        wr.flush();
        wr.close();

        return true;
    } catch (IOException e) {
        return false;
    }
}

// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpURLConnection connection) {
    try {
        StringBuilder str = new StringBuilder();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            str.append(line + System.getProperty("line.separator"));
        }
        return str.toString();
    } catch (IOException e) {
        return new String();
    }
}

1 个答案:

答案 0 :(得分:2)

您错过了查询变量q,这是必需参数。

尝试将您的请求网址更改为:https://api.twitter.com/1.1/search/tweets.json?count=2&q=test