我正在尝试使用仅应用程序承载令牌来获取https://api.twitter.com/1.1/search/tweets.json?q=nasa&count=5
的推文,该令牌已成功使用了消费者密钥和消费者秘密。但是我无法获取这些推文。这是我的代码:
public class SearchTweetsTask extends AsyncTask<String, Void, String> {
private static final String TWITTER_HOST = "api.twitter.com";
private static final String TWITTER_USER_AGENT = "TwitterMotion User Agent";
private Logger logger = Logger.getLogger();
@Override
protected String doInBackground(String... tokens) {
String endPointUrl = tokens[0];
HttpsURLConnection urlConnection = null;
try {
urlConnection = getHTTPSConnection("GET", endPointUrl);
urlConnection.setRequestProperty("Authorization",
"Bearer " + APPLICATION_ONLY_BEARER_TOKEN);
String jsonResponse = readResponse(urlConnection);
return responseAsJsonObject.toString();
}
catch (Exception ex) {
logger.e(ex);
return null;
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
@Override
protected void onPostExecute(String asyncTaskResult) {
logger.i(asyncTaskResult);
}
public static HttpsURLConnection getHTTPSConnection(String requestMethod, String endpointUrl)
throws IOException {
URL url = new URL(endpointUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("Host", TWITTER_HOST);
connection.setRequestProperty("User-Agent", TWITTER_USER_AGENT);
connection.setUseCaches(false);
return connection;
}
public static String readResponse(HttpsURLConnection connection) throws IOException {
BufferedReader bufferedReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + System.getProperty("line.separator"));
}
return stringBuilder.toString();
}
catch (IOException ex) {
throw ex;
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
}
}
在readRequest()
方法内部,connection
对象无法正常工作。我检查了connection.getResponseCode()
并返回了400
,而connection.getErrorStream()
返回了Error Code 86 “This method requires a GET or HEAD”
。
我从命令行尝试了cURL,它运行良好。
curl -X GET \
'https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular' \
-H 'Authorization: Bearer <Application Only Bearer Token>' \
-H 'Cache-Control: no-cache' \
-H 'Host: api.twitter.com' \
-H 'User-Agent: TwitterMotion User Agent'
它变得非常令人沮丧。预先感谢!
答案 0 :(得分:1)
如here所述,httpCon.setDoOutput(true)
隐式将请求方法设置为POST
,因为这是每当您要发送请求正文时的默认方法。
如果要使用GET
,请删除该行。