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

Search Tweets with pure Java 400 get Bad Request

我尝试使用搜索推文使用 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();
    }
}

您缺少一个查询变量 q,这是一个必需的参数。

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