gpt4 book ai didi

java - Twitter 通话请求

转载 作者:太空宇宙 更新时间:2023-11-04 14:17:56 25 4
gpt4 key购买 nike

我的 Twitter 请求源代码有问题。从 Twitter 返回的响应是空字符串。您能建议哪里可能出现问题吗?

我已经在 dev.twitter.com 上正常注册了我的应用程序。它称为到达次数。

此代码来自本教程:http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/

package count_reach_twitter;

//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;

/**
*
* @author Martin
*/
public class TwitterCall {

// Encodes the consumer key and secret to create the basic authorization key
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();
}
}

// Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection 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(HttpsURLConnection 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(); }
}

// Constructs the request for requesting a bearer token and returns that token as a string
private static String requestBearerToken(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys("My customer key","My customer secret key");

try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Reach Count");
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");

// Parse the JSON response into a JSON mapped object to fetch fields from.
System.out.println("Response: " + readResponse(connection));
System.out.println("End");
JSONObject obj = new JSONObject(readResponse(connection)); //(JSONObject)JSONValue.parse(readResponse(connection));
//obj.

if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");

return ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}

// Fetches the first tweet from a given user's timeline
public static String fetchTimelineTweet(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", "Reach Count");
connection.setRequestProperty("Authorization", "Bearer " + requestBearerToken("https://api.twitter.com/oauth2/token"));
connection.setUseCaches(false);


// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONArray obj = new JSONArray(readResponse(connection));//(JSONArray)JSONValue.parse(readResponse(connection));

if (obj != null) {
String tweet = ((JSONObject)obj.get(0)).get("text").toString();

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


}

主函数正在调用下一个方法:

System.out.println(TwitterCall.fetchTimelineTweet("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Dj_Fedy&count=50"));

谢谢

最佳答案

我不确定为什么你的代码会从 Twitter 收到 403 错误码。我能想到两件事:

  1. 根据Application-only authentication doc底部,当您在不支持仅应用程序身份验证的端点上使用不记名 token 时,会给出 403 响应。我无法确定仅应用程序身份验证是否允许在 statuses/user_timeline 上进行 GET
  2. 根据GET statuses/user_timeline doc ,只有当经过身份验证的用户“拥有”时间线或者是所有者批准的关注者时,您才能为 protected 用户请求推文。我不确定您是否属于这种情况。

关于java - Twitter 通话请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com