使用Java的TwitterAPI登录过程
我正在尝试使用3-legged构建TwitterSpring引导API,但是,当我运行代码时,它显示错误:HTTP请求可能不为null。 由于当时我已经尝试了4-5个小时的不同方法,我无法解决同样的问题 每次抛出“HTTP请求可能不为空” 我的控制器:使用Java的TwitterAPI登录过程,java,twitter-oauth,Java,Twitter Oauth,我正在尝试使用3-legged构建TwitterSpring引导API,但是,当我运行代码时,它显示错误:HTTP请求可能不为null。 由于当时我已经尝试了4-5个小时的不同方法,我无法解决同样的问题 每次抛出“HTTP请求可能不为空” 我的控制器: import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.H
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.HTTP;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class TwitterController {
@RequestMapping(value = "/twitterLogin", method = RequestMethod.GET)
public ModelAndView linkAuthorization() {
ModelAndView model = new ModelAndView("twitterLogin");
return model;
}
@RequestMapping(value = "/twittersignin", method = RequestMethod.GET)
public ModelAndView twitterLogin() {
ModelAndView model = new ModelAndView("success");
String requestTokenUrl = "https://api.twitter.com/oauth/request_token";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
RequestOauthHeaderGenerator generator = new RequestOauthHeaderGenerator("http://127.0.0.1:8080/success",
"8gviQnqApIePyzx5Fm84K0jCg", "signatureMethod", "oauthTimestamp", "oauthNounce", "1.0");
String header = generator.generateHeader("POST", requestTokenUrl);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", header);
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authorization", "header");
String header1 = HTTP.toString(jsonObject);
HttpPost httpPost1 = new HttpPost(header1);
StringEntity requestString = new StringEntity("");
httpPost1.setEntity(requestString);
HttpResponse initialRespone = httpClient.execute(httpPost1);
if (initialRespone.getStatusLine().getStatusCode() == 200) {
String initialResult = EntityUtils.toString(initialRespone.getEntity());
if (initialResult != null && initialResult != "") {
JSONObject jsonObjectInitialResult = new JSONObject(initialResult);
TwitterResponseDetails twitterResponseDetails = new TwitterResponseDetails();
String oauthConfirmation = jsonObjectInitialResult.get("oauth_callback_confirmed").toString();
if (oauthConfirmation != null && oauthConfirmation != "" && oauthConfirmation != "false") {
twitterResponseDetails.setOauthConfirmation(oauthConfirmation);
String initialToken = jsonObjectInitialResult.get("oauth_token").toString();
if (initialToken != null && initialToken != "") {
twitterResponseDetails.setToken1(initialToken);
}
String initialSecretToken = jsonObjectInitialResult.get("oauth_token_secret").toString();
if (initialSecretToken != null && initialSecretToken != "") {
twitterResponseDetails.setSecretToken1(initialSecretToken);
}
String authenticationUrl = "https://api.twitter.com/oauth/authenticate?oauth_token="
+ initialToken;
HttpGet httpGetAuthenticationUrl = new HttpGet(authenticationUrl);
HttpResponse intermediateResponse = httpClient.execute(httpGetAuthenticationUrl);
System.out.println("intermediateResponse : " + intermediateResponse);
if (intermediateResponse.getStatusLine().getStatusCode() == 200) {
String intermediateResult = EntityUtils.toString(intermediateResponse.getEntity());
if (intermediateResult != null && intermediateResult != "") {
JSONObject jsonObjectIntermediateResult = new JSONObject(intermediateResult);
String intermediateToken = jsonObjectIntermediateResult.get("oauth_token").toString();
if (intermediateToken != null && intermediateToken != "") {
twitterResponseDetails.setToken2(intermediateToken);
}
String oauthVerifier = jsonObjectInitialResult.get("oauth_verifier").toString();
if (oauthVerifier != null && oauthVerifier != "") {
twitterResponseDetails.setOauthVerifier(oauthVerifier);
}
if (initialToken == intermediateToken) {
String clientRediectUrl = "https://callbackurl?oauth_token=" + intermediateToken
+ "&" + "oauth_verifier=" + oauthVerifier;
HttpGet httpGetClientRedirectUrl = new HttpGet(clientRediectUrl);
HttpResponse clientRedirectResponse = httpClient.execute(httpGetClientRedirectUrl);
if (initialRespone.getStatusLine().getStatusCode() == 200) {
System.out.println("ClientRedirectResponse : " + clientRedirectResponse);
String accessTokenUrl = "https://api.twitter.com/oauth/access_token?oauth_token="
+ intermediateToken + "&" + "oauth_verifier=" + oauthVerifier;
HttpPost httpPostAccesstokenUrl = new HttpPost(accessTokenUrl);
HttpResponse accessTokenResponse = httpClient.execute(httpPostAccesstokenUrl);
if (accessTokenResponse.getStatusLine().getStatusCode() == 200) {
String accessTokenResult = EntityUtils
.toString(accessTokenResponse.getEntity());
if (accessTokenResult != null && accessTokenResult != "") {
JSONObject jsonObjectFinalResult = new JSONObject(accessTokenResult);
String finalToken = jsonObjectFinalResult.get("oauth_token").toString();
if (finalToken != null && finalToken != "") {
twitterResponseDetails.setToken3(finalToken);
}
String finalSecretToken = jsonObjectFinalResult
.get("oauth_token_secret").toString();
if (finalSecretToken != null && finalSecretToken != "") {
twitterResponseDetails.setSecretToken2(finalSecretToken);
}
} else {
System.out.println("Incorrect access token");
}
} else {
System.out.println(" Incorrect Tokens");
}
}
} else {
System.out.println(" Incorrect intermediateResult");
}
} else {
System.out.println(" Incorrect Conformation");
}
} else {
System.out.println("Incorrect InitialResult");
}
}
}
}
} catch (
Exception e) {
e.printStackTrace();
}
return model;
}
}
标题生成器:
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public class RequestOauthHeaderGenerator {
public String callbackUrl;
public String consumerKey;
public String oauthNounce;
public String signatureMethod;
public String oauthTimestamp;
public String oauthVersion;
public RequestOauthHeaderGenerator(String callbackUrl, String consumerKey, String oauthNounce,
String signatureMethod, String oauthTimestamp, String oauthVersion) {
this.callbackUrl = callbackUrl;
this.consumerKey = consumerKey;
this.oauthNounce = getNonce();
this.signatureMethod = "HMAC-SHA1";
this.oauthTimestamp = getTimestamp();
this.oauthVersion = oauthVersion;
}
private static final String oauth_callback = "oauth_callback";
private static final String oauth_consumer_key = "oauth_consumer_key";
private static final String oauth_nonce = "oauth_nonce";
private static final String oauth_signature = "oauth_signature";
private static final String oauth_signature_method = "oauth_signature_method";
private static final String oauth_timestamp = "oauth_timestamp";
private static final String oauth_version = "oauth_version";
private static final String HMAC_SHA1 = "SHA-1";
public String generateHeader(String httpMethod, String url) throws NoSuchAlgorithmException {
StringBuilder base = new StringBuilder();
String baseSignatureString = generateSignatureBaseString(httpMethod, url);
String signature = encryptUsingHmacSHA1(baseSignatureString);
System.out.println(signature);
base.append("OAuth ");
append(base, oauth_callback, callbackUrl);
append(base, oauth_consumer_key, consumerKey);
append(base, oauth_nonce, oauthNounce);
append(base, oauth_signature, signature);
append(base, oauth_signature_method, signatureMethod);
append(base, oauth_timestamp, oauthTimestamp);
base.deleteCharAt(base.length() - 1);
System.out.println("header : " + base.toString());
append(base, "oauth_version", oauthVersion);
System.out.println("base : " + base);
return base.toString();
}
String generateSignatureBaseString(String httpMethod, String url) {
Map<String, String> params = new HashMap<>();
put(params, oauth_callback, callbackUrl);
put(params, oauth_consumer_key, consumerKey);
put(params, oauth_nonce, getNonce());
put(params, oauth_signature_method, signatureMethod);
put(params, oauth_timestamp, getTimestamp());
put(params, oauth_version, oauthVersion);
Map<String, String> sortedParams = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
LinkedHashMap::new));
StringBuilder base = new StringBuilder();
sortedParams.entrySet().forEach(entry -> {
base.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
});
base.deleteCharAt(base.length() - 1);
String baseString = httpMethod.toUpperCase() + "&" + encode(url) + "&" + encode(base.toString());
System.out.println("baseString : " + baseString);
return baseString;
}
private static String encryptUsingHmacSHA1(String input) throws NoSuchAlgorithmException {
try {
MessageDigest md = MessageDigest.getInstance(HMAC_SHA1);
byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static String encode(String value) {
String encoded = "";
try {
encoded = URLEncoder.encode(value, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
String sb = "";
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
sb += "%2A";
} else if (focus == '+') {
sb += "%20";
} else if (focus == '%' && i + 1 < encoded.length() && encoded.charAt(i + 1) == '7'
&& encoded.charAt(i + 2) == 'E') {
sb += '~';
i += 2;
} else {
sb += focus;
}
}
return sb.toString();
}
private void put(Map<String, String> map, String key, String value) {
map.put(encode(key), encode(value));
}
private void append(StringBuilder builder, String key, String value) {
builder.append(encode(key)).append("=\"").append(encode(value)).append("\",");
}
private String getNonce() {
return UUID.randomUUID().toString().replace("-", "");
}
private String getTimestamp() {
return Math.round((new Date()).getTime() / 1000.0) + "";
}
}
import java.math.biginger;
导入java.net.urlcoder;
导入java.nio.charset.StandardCharset;
导入java.security.MessageDigest;
导入java.security.NoSuchAlgorithmException;
导入java.util.Date;
导入java.util.HashMap;
导入java.util.LinkedHashMap;
导入java.util.Map;
导入java.util.UUID;
导入java.util.stream.collector;
公共类请求OAuthHeaderGenerator{
公共字符串回调URL;
公共消费市场;
公共字符串oauthNounce;
公共字符串签名方法;
公共字符串时间戳;
公共字符串oauthVersion;
公共请求OAuthHeaderGenerator(字符串回调URL、字符串consumerKey、字符串OAuthNonce、,
字符串签名方法、字符串oauthTimestamp、字符串oauthVersion){
this.callbackUrl=callbackUrl;
this.consumerKey=consumerKey;
this.oauthNounce=getNonce();
this.signatureMethod=“HMAC-SHA1”;
this.oauthTimestamp=getTimestamp();
this.oauthVersion=oauthVersion;
}
私有静态最终字符串oauth\u callback=“oauth\u callback”;
私有静态最终字符串oauth\u consumer\u key=“oauth\u consumer\u key”;
私有静态最终字符串oauth\u nonce=“oauth\u nonce”;
私有静态最终字符串oauth_签名=“oauth_签名”;
私有静态最终字符串oauth\u signature\u method=“oauth\u signature\u method”;
私有静态最终字符串oauth_timestamp=“oauth_timestamp”;
私有静态最终字符串oauth_version=“oauth_version”;
私有静态最终字符串HMAC_SHA1=“SHA-1”;
公共字符串生成器标头(字符串httpMethod,字符串url)抛出NoSuchAlgorithmException{
StringBuilder base=新的StringBuilder();
String baseSignatureString=generateSignatureBaseString(httpMethod,url);
字符串签名=加密使用HMACSHA1(baseSignatureString);
系统输出打印号(签名);
base.append(“OAuth”);
append(base、oauth_回调、callbackUrl);
追加(基本、oauth\u消费者密钥、消费者密钥);
附加(base、oauth\u nonce、oauthNounce);
附加(基本、oauth_签名、签名);
append(base、oauth\u signature\u方法、signatureMethod);
追加(基本、oauth_时间戳、oauth时间戳);
base.deleteCharAt(base.length()-1);
System.out.println(“标题:+base.toString());
附加(基本,“oauth_版本”,oauth版本);
System.out.println(“base:+base”);
返回base.toString();
}
String generateSignatureBaseString(字符串httpMethod,字符串url){
Map params=新的HashMap();
put(参数、oauth_回调、回调URL);
put(参数、oauth_消费者_密钥、消费者密钥);
put(params,oauth_nonce,getNonce());
put(参数、oauth\u签名方法、签名方法);
put(params,oauth_timestamp,getTimestamp());
put(参数,oauth_版本,oauth版本);
Map-sortedParams=params.entrySet().stream().sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(oldValue,newValue)->oldValue,
LinkedHashMap::new));
StringBuilder base=新的StringBuilder();
sortedParams.entrySet().forEach(条目->{
base.append(entry.getKey()).append(“=”).append(entry.getValue()).append(“&”);
});
base.deleteCharAt(base.length()-1);
String baseString=httpMethod.toUpperCase()+“&”+encode(url)+“&”+encode(base.toString());
System.out.println(“baseString:+baseString”);
返回基串;
}
私有静态字符串加密使用HMACSHA1(字符串输入)抛出NoSuchAlgorithmException{
试一试{
MessageDigest md=MessageDigest.getInstance(HMAC_SHA1);
byte[]messageDigest=md.digest(input.getBytes(StandardCharsets.UTF_8));
BigInteger否=新的BigInteger(1,messageDigest);
字符串hashtext=no.toString(16);
while(hashtext.length()<32){
hashtext=“0”+hashtext;
}
返回hashtext;
}捕获(无算法异常){
抛出新的运行时异常(e);
}
}
私有静态字符串编码(字符串值){
字符串编码=”;
试一试{
encoded=urlcoder.encode(值为“UTF-8”);
}捕获(例外e){
e、 printStackTrace();
}
串某人“”;
焦焦;
for(int i=0;i
您的帖子中没有问题。请更新您的任务