본문 바로가기

Back end/Java

자바 JAVA HttpURLConnection

728x90
public String reqOauth_refreshToken(String requestUrl, String refresh_token) throws IOException {

    String responseVal = "";

    //요청할 url
    URL url = new URL(requestUrl);
    // 문자열로 URL 표현
    System.out.println("요청 URL :" + url.toExternalForm());

    // 파라미터 세팅
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("refresh_token", refresh_token); // Key, Value 세팅
    params.put("grant_type", "refresh_token");

    StringBuilder postData = new StringBuilder();
    for(Map.Entry<String,Object> param : params.entrySet()) {
        if(postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    // HTTP Connection 구하기
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // 요청 방식 설정 ( GET or POST or .. 별도로 설정하지않으면 GET 방식 )
    conn.setRequestMethod("POST");
    conn.setDoOutput(true); // 이 항목을 추가
    
    // 전송시 Authorization 타입에 맞게 세팅, conn.setRequestProperty(token_type, access_token)
    conn.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode("clientId:secretKey".getBytes()));
    //conn.setRequestProperty("Authorization","Bearer " + access_token);
    
    // 연결 타임아웃 설정
    conn.setConnectTimeout(5000); // 1s = 1000
    // 읽기 타임아웃 설정
    conn.setReadTimeout(5000); // 1s = 1000
    conn.getOutputStream().write(postDataBytes); // POST 호출

    // 요청 방식 구하기
    System.out.println("getRequestMethod():" + conn.getRequestMethod());
    // 응답 콘텐츠 유형 구하기
    System.out.println("getContentType():" + conn.getContentType());
    // 응답 코드 구하기
    System.out.println("getResponseCode():"    + conn.getResponseCode());
    // 응답 메시지 구하기
    System.out.println("getResponseMessage():" + conn.getResponseMessage());


    // 응답 헤더의 정보를 모두 출력
    for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
        for (String value : header.getValue()) {
            System.out.println("응답헤더 = " + header.getKey() + " : " + value);
        }
    }

    // 응답 내용(BODY) 구하기
    try (InputStream in = conn.getInputStream();
         ByteArrayOutputStream out = new ByteArrayOutputStream()) {

        byte[] buf = new byte[1024 * 8];
        int length = 0;
        while ((length = in.read(buf)) != -1) {
            out.write(buf, 0, length);
        }

        //응답 data
        String data = new String(out.toByteArray(), "UTF-8");
        System.out.println("응답body = " + new String(out.toByteArray(), "UTF-8"));

        //JSON data value 꺼내기
        JSONObject jObject = new JSONObject(data);
        String access_token = jObject.getString("access_token");

        responseVal = access_token;

    }

    return responseVal;
}
728x90