Процесс входа в API Twitter с использованием Java - PullRequest
0 голосов
/ 25 февраля 2020

Я пытаюсь создать Twitter Spring Boot API с использованием 3-х сторон, но когда я запускал код, он показывал ошибку: HTTP-запрос не может быть нулевым. Поскольку я пробовал другой метод в течение 4-5 часов, даже тогда я не могу решить проблему для того же самого.

Каждый раз, когда он выдавал «HTTP-запрос не может быть пустым».

Мой контроллер:

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) + "";
    }
}
...