뤼준석
60
2015-09-07 15:04:35
1
2064

Tistory OAuth 2.0 인증 예제 질문입니다.


import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.ssl.*;

public class AccessTokenGetter {

    public static void main(String[] args) throws Exception {

        String id = "lljjssjjll@daum.net";
        String pw = "비공개";
        String blogUrl = filterBlogUrl("http://ljs0407.tistory.com/");
        
        /* 티스토리 로그인 */
        System.out.println("로그인 중...");
        List<String> cookies = loginTistory(id, pw);
        System.out.println("쿠키값 : " + cookies);
        System.out.println("로그인 완료...");
        System.out.println();
        
        String clientId = "비공개";
String secretKey = "비공개";
System.out.println("client id : " + clientId); System.out.println("secrek key : " + secretKey); /* client_id와 secret_key를 이용하여 auth_code를 획득 */ System.out.println("Authorization Code를 받아오는 중..."); String authCode = acquireAuthCode(cookies, blogUrl, clientId); System.out.println("[AUTH CODE] " + authCode); System.out.println(); // /* 최종적으로 access_token을 획득 */ // System.out.println("Access Token을 받아오는 중..."); // String accessToken = acquireAccessToken( // cookies, clientId, secretKey, blogUrl, authCode); // System.out.println("[ACCESS TOKEN] " + accessToken); } public static String filterBlogUrl(String blogUrl) { blogUrl = blogUrl.replace("http://", ""); blogUrl = blogUrl.replace(".tistory.com", ""); blogUrl = blogUrl.replace("/", ""); return blogUrl; } public static List<String> loginTistory(String id, String pw) throws MalformedURLException, IOException { String url = "https://www.tistory.com/auth/login" + "?redirectUrl=http%3A%2F%2Fwww.tistory.com"; StringBuilder params = new StringBuilder(); addParam(params, "loginId", id); addParam(params, "password", pw); return postForCookies(url, params.toString()); } public static String acquireAuthCode(List<String> cookies, String blogUrl, String clientId) throws MalformedURLException, IOException { String url = "https://www.tistory.com/oauth/authorize?"; url += "client_id=" + clientId; url += "&redirect_uri=" + URLEncoder.encode( "http://" + blogUrl + ".tistory.com", "utf-8"); url += "&response_type=code"; String authCode = postForContent(cookies, url, ""); int idx = authCode.indexOf("?code=") + 6; authCode = authCode.substring(idx); idx = authCode.indexOf("'; }"); authCode = authCode.substring(0, idx); url = "http://" + blogUrl + ".tistory.com?code=" + authCode; postForContent(cookies, url, ""); return authCode; } // public static String acquireAccessToken(List<String> cookies, // String clientId, String secretKey, String blogUrl, String authCode) // throws MalformedURLException, IOException { // String url = "https://www.tistory.com/oauth/access_token?"; // url += "client_id=" + clientId; // url += "&client_secret=" + secretKey; // url += "&redirect_uri=" // + URLEncoder.encode( // "http://" + blogUrl + ".tistory.com", "utf-8"); // url += "&code=" + authCode; // url += "&grant_type=authorization_code"; // // String accessToken = postForContent(cookies, url, ""); // accessToken = accessToken.replace("access_token=", ""); // return accessToken; // } private static List<String> postForCookies(String url, String params) throws MalformedURLException, IOException { if (params == null) params = ""; URLConnection tmp = new URL(url).openConnection(); if (tmp instanceof HttpURLConnection) { HttpURLConnection conn = (HttpURLConnection) tmp; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Connection", "keep-alive"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(params); dos.flush(); dos.close(); CookieHandler.setDefault(new CookieManager()); return conn.getHeaderFields().get("Set-Cookie"); } else { HttpsURLConnection conn = (HttpsURLConnection) tmp; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Connection", "keep-alive"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(params); dos.flush(); dos.close(); CookieHandler.setDefault(new CookieManager()); return conn.getHeaderFields().get("Set-Cookie"); } } private static String postForContent(List<String> cookies, String url, String params) throws MalformedURLException, IOException { if (params == null) params = ""; URLConnection tmp = new URL(url).openConnection(); if (tmp instanceof HttpURLConnection) { HttpURLConnection conn = (HttpURLConnection) tmp; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Connection", "keep-alive"); for (String cookie : cookies) conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(params); dos.flush(); dos.close(); return retrieve(new BufferedReader(new InputStreamReader( conn.getInputStream(), "UTF-8"))); } else { HttpsURLConnection conn = (HttpsURLConnection) tmp; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Connection", "keep-alive"); for (String cookie : cookies) conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(params); dos.flush(); dos.close(); return retrieve(new BufferedReader(new InputStreamReader( conn.getInputStream(), "UTF-8"))); } } private static void addParam(StringBuilder sb, String key, String value) { try { value = URLEncoder.encode(value, "utf-8"); } catch (UnsupportedEncodingException e) { } if (sb.length() == 0) sb.append(key + "=" + value); else sb.append("&" + key + "=" + value); } private static String retrieve(BufferedReader br) throws IOException { StringBuilder sb = new StringBuilder(); String inputLine; while ((inputLine = br.readLine()) != null) sb.append(inputLine); return sb.toString(); } }

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -5

at java.lang.String.substring(Unknown Source)

at AccessTokenGetter.acquireAuthCode(AccessTokenGetter.java:69)

at AccessTokenGetter.main(AccessTokenGetter.java:28)

빨간색으로 표시한 메소드 부분에서 계속 에러가 나옵니다.  로그인까지는 여차여차해서 쿠키값 가져오는데 성공했습니다. 문제는 authorization code 를 가져오는 메소드에서 String authCode 가 자꾸 null 이 나온다는 겁니다.. OAuth 2.0 접해보신분 답변좀 부탁드려요. 올바른 authCode를 가져오려면 어떤식으로 수정해야 할까요..

0
0
  • 답변 1

  • vichara
    289
    2015-09-07 16:06:15

    Scribe 쓰세요 토큰발급후 주소랑 파라미터만 넘기면 됩니다  

    Oaurhrequest 사용하시면 되요

    폰이라 짧게씁니다

    0
  • 로그인을 하시면 답변을 등록할 수 있습니다.