아 래 형식으로 REQUEST를 던집니다. 401 에러가 나오는데 401 에러가 나오는 형식이 권한이 없는걸루 알고있습니다 혹시 다른 파라미터라도 추가 해야할까요?
try {
url = new URL(getPersnalInfoUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty(“Bearer”, access_token);
conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
conn.setRequestProperty(“charset”, “utf-8”);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();
log.info("header 전송");
int responseCode = conn.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + getPersnalInfoUrl);
System.out.println("Response Code : " + responseCode);
isr = new InputStreamReader(conn.getInputStream());
reader = new BufferedReader(isr);
final StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String responseParam = buffer.toString();
System.out.println(responseParam);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tom
#2
@tjdrhs333
아래와 같이 수정하세요.
conn.setRequestProperty("Authorization", "Bearer " +access_token.trim());
그렇게 수정해서 보냈을경우 401 unAuthorization 에러가 납니다. 토큰 값도 제대로 들고옵니다.
tom
#4
@tjdrhs333
테스트 코드를 확인해 보세요.
package com.company;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
public class Main {
public static void main(String[] args) {
// write your code here
final String AUTH_HOST = "https://kauth.kakao.com";
final String tokenRequestUrl = AUTH_HOST + "/oauth/token";
String CLIENT_ID = ""; // 해당 앱의 REST API KEY 정보. 개발자 웹사이트의 대쉬보드에서 확인 가능
String REDIRECT_URI = ""; // 해당 앱의 설정된 uri. 개발자 웹사이트의 대쉬보드에서 확인 및 설정 가능
String code = ""; // 로그인 과정중 얻은 authorization code 값
String getPersnalInfoUrl = "https://kapi.kakao.com/v1/user/me"; // 로그인후 사용자 정보 받아 오기위한 url
String access_token = "access_token";
String token_type = "token_type";
HttpsURLConnection conn = null;
OutputStreamWriter writer = null;
BufferedReader reader = null;
InputStreamReader isr= null;
URL url = null;
try {
final String params = String.format("grant_type=authorization_code&client_id=%s&redirect_uri=%s&code=%s",
CLIENT_ID, REDIRECT_URI, code);
url = new URL(tokenRequestUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(params);
writer.flush();
final int responseCode = conn.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + tokenRequestUrl);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
isr = new InputStreamReader(conn.getInputStream());
reader = new BufferedReader(isr);
final StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String responseParam = buffer.toString();
System.out.println(responseParam);
access_token = responseParam.substring(responseParam.indexOf("access_token") + access_token.length() + 3 , responseParam.indexOf(token_type) - 3);
System.out.println("access_token:" + access_token);
} catch (IOException e) {
e.printStackTrace();
} finally {
// clear resources
if (writer != null) {
try {
writer.close();
} catch(Exception ignore) {
}
}
if (reader != null) {
try {
reader.close();
} catch(Exception ignore) {
}
}
if (isr != null) {
try {
isr.close();
} catch(Exception ignore) {
}
}
}
if (conn != null) {
conn.disconnect();
}
try {
url = new URL(getPersnalInfoUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " +access_token.trim());
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();
// log.info("header 전송");
int responseCode = conn.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + getPersnalInfoUrl);
System.out.println("Response Code : " + responseCode);
isr = new InputStreamReader(conn.getInputStream());
reader = new BufferedReader(isr);
final StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String responseParam = buffer.toString();
System.out.println(responseParam);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
access_token값을 다시 확인 해볼까요?
2017-07-17 13:42:07.431 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : {“access_token”:“LnxsjwYxCZrP9kgFhZaprLwMQ1hnGa3hsNfI0AopdgcAAAFdTtqxfQ”,“token_type”:“bearer”,“refresh_token”:“09V3l2xnMsMoDpWQOYcbBuSWjf2nLdrI7kz8TwopdgcAAAFdTtqxew”,“expires_in”:21599,“scope”:“account_email profile”}
2017-07-17 13:42:07.431 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : access_token:LnxsjwYxCZrP9kgFhZaprLwMQ1hnGa3hsNfI0AopdgcAAAFdTtqxfQ
2017-07-17 13:42:07.431 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : disconnect
2017-07-17 13:42:07.431 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : 사용자 정보 얻기 시작
2017-07-17 13:42:07.512 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : Sending ‘POST’ request to URL : https://kapi.kakao.com/v1/user/me
2017-07-17 13:42:07.512 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : Response Code : 401
2017-07-17 13:42:07.513 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : access_token :LnxsjwYxCZrP9kgFhZaprLwMQ1hnGa3hsNfI0AopdgcAAAFdTtqxfQ
2017-07-17 13:42:07.513 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : Unauthorized/v1/user/me
2017-07-17 13:42:07.513 INFO 31604 — [p-nio-80-exec-9] kr.co.earlook.web.MainController : LnxsjwYxCZrP9kgFhZaprLwMQ1hnGa3hsNfI0AopdgcAAAFdTtqxfQ
tom
#7
@tjdrhs333
/v1/user/me 호출 시 401 응답이면 access token이 제대로 전달이 안된네요.
아래와 같이 access token이 요청되었는지 확인해 보세요.
conn.setRequestProperty("Authorization", "Bearer " + access_token);
그렇게도 보내봤습니다 ㅠㅠ 그렇게 보내니 400이 나오네요
tom
#9
@tjdrhs333
400은 파라미터 값이 누락 되면 나오는건데요 ㅠ
제가 위에서 수정해서 드린 테스트 코드에 아래 값만 채워서 호출하면 사용자 정보가 나와야 합니다.
String CLIENT_ID = "";
String REDIRECT_URI = "";
String code = ""; /
사용자 정보값 받아올때 CLIENT_ID 랑 REDIRECT_URI . CODE 필요 없지 않나요?
GET/POST /v1/user/me HTTP/1.1
Host: kapi.kakao.com
Authorization: Bearer {access_token}
Content-type: application/x-www-form-urlencoded;charset=utf-8
여기 보시면 파라미터는 들어기자 않습니다. ㅠㅠ
tom
#11
@tjdrhs333
네 사용자 정보 얻어 올 때는 위에 정보는 필요 없습니다.
제가 위에 설명한 것은 값을 채우면 테스트 코드를 통해서 사용자 정보가 정상적으로 나와야 한다는 것을 말씀드린거에요. 400/401 에러 코드가 아닌.
400 나오네요 ㅠㅠ 테스트 코드 복붙해서 key값 그런것만 수정했는데 400이 나오네요
final String AUTH_HOST = "https://kauth.kakao.com";
final String tokenRequestUrl = AUTH_HOST + "/oauth/token";
String CLIENT_ID = "8d5b47c9fabfc0eae6ac2477fe0f1453"; // 해당 앱의 REST API KEY 정보. 개발자 웹사이트의 대쉬보드에서 확인 가능
String REDIRECT_URI = "http://spiritlook.cafe24.com/app"; // 해당 앱의 설정된 uri. 개발자 웹사이트의 대쉬보드에서 확인 및 설정 가능
String code = request.getQueryString(); // 로그인 과정중 얻은 authorization code 값
String getPersnalInfoUrl = "https://kapi.kakao.com/v1/user/me"; // 로그인후 사용자 정보 받아 오기위한 url
String access_token = "access_token";
String token_type = "token_type";
HttpsURLConnection conn = null;
OutputStreamWriter writer = null;
BufferedReader reader = null;
InputStreamReader isr= null;
URL url = null;
try {
final String params = String.format("grant_type=authorization_code&client_id=%s&redirect_uri=%s&",
CLIENT_ID, REDIRECT_URI) + code;
url = new URL(tokenRequestUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(params);
writer.flush();
final int responseCode = conn.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + tokenRequestUrl);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
isr = new InputStreamReader(conn.getInputStream());
reader = new BufferedReader(isr);
final StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String responseParam = buffer.toString();
System.out.println(responseParam);
access_token = responseParam.substring(responseParam.indexOf("access_token") + access_token.length() + 3 , responseParam.indexOf(token_type) - 3);
System.out.println("access_token:" + access_token);
} catch (IOException e) {
e.printStackTrace();
} finally {
// clear resources
if (writer != null) {
try {
writer.close();
} catch(Exception ignore) {
}
}
if (reader != null) {
try {
reader.close();
} catch(Exception ignore) {
}
}
if (isr != null) {
try {
isr.close();
} catch(Exception ignore) {
}
}
}
if (conn != null) {
conn.disconnect();
}
try {
url = new URL(getPersnalInfoUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " +access_token.trim());
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();
// log.info("header 전송");
int responseCode = conn.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + getPersnalInfoUrl);
System.out.println("Response Code : " + responseCode);
isr = new InputStreamReader(conn.getInputStream());
reader = new BufferedReader(isr);
final StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String responseParam = buffer.toString();
System.out.println(responseParam);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tom
#14
@tjdrhs333
혹시… 동일한 code 값으로 테스트하고 계신건 아니죠? code 값을 재사용하시면 400 응답이 옵니다.
위에 붙여 놓은 코드에는 문제가 없어 보입니다. 중요 값만 바꿔서 확인해 봤는데 됩니다.