输出以及堆栈跟踪是:
https://api.twitter.com/oauth/authorize?oauth_token=wUVGSompJWvIZc5rHxQ9PEMLT7zDWuRKNx3S6RxF9cs
mZWtTPuWnBDiTuCgIclTID41vpES9juxTPOsoYpwB04
mZWtTPuWnBDiTuCgIclTID41vpES9juxTPOsoYpw
Exception in thread "main" net.oauth.exception.OAuthException: HTTP/1.0 401 Unauthorized
at net.oauth.consumer.OAuth1Consumer.createOAuthTokenResponse(OAuth1Consumer.java:142)
at net.oauth.consumer.OAuth1Consumer.requestAccessToken(OAuth1Consumer.java:249)
at net.oauth.consumer.OAuth1Consumer.requestAccessToken(OAuth1Consumer.java:226)
at com.auth.Test1OAuth1.main(Test1OAuth1.java:84)
测试代码如下:package com.auth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import net.oauth.consumer.OAuth1Consumer;
import net.oauth.exception.OAuthException;
import net.oauth.http.HttpClient;
import net.oauth.provider.OAuth1ServiceProvider;
import net.oauth.signature.OAuthSignature;
import net.oauth.signature.impl.OAuthHmacSha1Signature;
import net.oauth.token.oauth1.RequestToken;
import net.oauth.token.oauth1.AccessToken;
public class Test1OAuth1
{
public static void main(String[] args) throws OAuthException, IOException,
URISyntaxException
{
String client_id = "Consumer key";
String client_secret = "Consumer secret";
OAuth1Consumer consumer = new OAuth1Consumer(client_id, client_secret,
new OAuth1ServiceProvider(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/authorize",
"https://api.twitter.com/oauth/access_token"));
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", "xxx.xxx.xxxx.xxx");
System.setProperty("proxyPort", "3128");
HttpClient client = new HttpProxyClient();
consumer.setClient(client);
OAuthSignature oAuthSignature = new OAuthHmacSha1Signature();
RequestToken requestToken = consumer.requestUnauthorizedToken(null,
"http://127.0.0.1:8080", null, oAuthSignature);
Map<String, String[]> map = new HashMap<String, String[]>();
String url = consumer
.createOAuthUserAuthorizationUrl(requestToken, map);
System.out.println(url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String verify = br.readLine();
System.out.println(verify);
AccessToken accessToken = consumer.requestAccessToken(null,
requestToken, verify, oAuthSignature);
System.out.println(accessToken.getToken());
System.out.println(accessToken.getTokenSecret());
}
}
HttpProxyClient 类与 HttpDefaultClient 相同,不同之处如下:
if (System.getProperty("proxySet").equals("true"))
{
if (null == proxyLocation)
{
proxyLocation = new InetSocketAddress(
System.getProperty("proxyHost"),
Integer.parseInt(System.getProperty("proxyPort")));
if (null == proxy)
{
proxy = new Proxy(Proxy.Type.HTTP, proxyLocation);
}
}
URLConnection uc = new URL(s).openConnection(proxy);
urlConnection = (HttpURLConnection) uc;
}
else
{
urlConnection = (HttpURLConnection) new URL(s).openConnection();
}