我编写了一个程序来获取用户的个人资料信息。,使用 Twitter API 1.1 当多个用户 id 以逗号分隔时,会发生以下错误
{"errors":[{"message":"Could not authenticate you","code":32}]}
代码如下
package com.demo.twitter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.demo.fb.RESTWebInvoke;
public class CrawlTwitterUserDetails
{
private static String encode(String value)
{
String encoded = null;
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
StringBuilder buf = new StringBuilder(encoded.length());
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buf.append("%2A");
} else if (focus == '+') {
buf.append("%20");
} else if (focus == '%' && (i + 1) < encoded.length()
&& encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
buf.append('~');
i += 2;
} else {
buf.append(focus);
}
}
return buf.toString();
}
private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException
{
SecretKey secretKey = null;
byte[] keyBytes = keyString.getBytes();
secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] text = baseString.getBytes();
return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}
public static void main(String args[]){
String oauth_token = "xxxxxxxxxx";
String oauth_token_secret = "xxxxxxxxxxx";
JSONObject jsonresponse = new JSONObject();
// generate authorization header
String get_or_post = "GET";
String oauth_signature_method = "HMAC-SHA1";
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here
// get the timestamp
Calendar tempcal = Calendar.getInstance();
long ts = tempcal.getTimeInMillis();// get current time in milliseconds
String oauth_timestamp = (new Long(ts/1000)).toString(); // then divide by 1000 to get seconds
// the parameter string must be in alphabetical order, "text" parameter added at end
String parameter_string = "oauth_consumer_key=" + "PWf1xDrJTqwZ99uHwMNrww" + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method +
"&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0&user_id="+encode("74663822")+encode(",")+encode("262131890");
System.out.println("parameter_string=" + parameter_string);
String twitter_endpoint = "https://api.twitter.com/1.1/users/lookup.json";
String twitter_endpoint_host = "api.twitter.com";
String twitter_endpoint_path = "/1.1/users/lookup.json";
String signature_base_string = get_or_post + "&"+ encode(twitter_endpoint) + "&" + encode(parameter_string);
System.out.println("signature_base_string=" + signature_base_string);
String oauth_signature = "";
try {
oauth_signature = computeSignature(signature_base_string, "ZxD5KKf624TDxwrhg92QdpXjXJYu6w02EYr2PNEDAI" + "&" + encode(oauth_token_secret));
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String authorization_header_string = "OAuth oauth_consumer_key=\"" + "PWf1xDrJTqwZ99uHwMNrww" + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp +
"\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
System.out.println("authorization_header_string=" + authorization_header_string);
RESTWebInvoke followers = new RESTWebInvoke(twitter_endpoint, false);
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", encode("74663822")+URLDecoder.decode(",")+encode("262131890"));
HashMap<String, String> header = new HashMap<String, String>();
header.put("Authorization", authorization_header_string);
String response = null;
JSONObject tmp = null;
try
{
response = followers.webGet("", params, header);
System.out.println(response);
}
catch(Exception e){
System.out.println(e);
}
}
}