반응형
Recent Posts
Recent Comments
관리 메뉴

개발잡부

[java] HTTP 통신하기 본문

JAVA/java

[java] HTTP 통신하기

닉의네임 2022. 1. 18. 15:13
반응형

HTTP 통신으로 API 호출하기 

 

build.gradle

plugins {
    id 'org.springframework.boot' version '2.6.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.ldh'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
   
    // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
    // https://mvnrepository.com/artifact/com.google.code.gson/gson
    implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9'
    // https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
    implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

 

HttpUtils.java

package com.ldh.embed.http;

import com.google.gson.Gson;
import org.json.simple.JSONObject;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;

public class HttpUtils {

    private static String  encoding ="UTF-8";

    public HashMap post(String sendUrl , HashMap<String,Object> data , String sendType ) throws Exception {
        JSONObject jobj = null;
        URL url = new URL(sendUrl);
        Gson gson = new Gson();
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        byte[] postDataBytes = null ;

        if(sendType.equals("json")) {
            conn.setRequestProperty("Content-Type", "application/json");

            String strJson = gson.toJson(data);
            postDataBytes = strJson.getBytes("UTF-8");
        }else {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            StringBuilder postData = new StringBuilder();
            for (HashMap.Entry<String, Object> param : data.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"));
            }
            postDataBytes = postData.toString().getBytes("UTF-8");
        }

        if(postDataBytes !=null && postDataBytes.length != 0){
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);

            Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuffer sf = new StringBuffer();

            for (int c; (c = in.read()) >= 0;)    sf.append((char)c);
            conn.disconnect();

            String resStr = sf.toString();
            HashMap resMap = new HashMap();

            return gson.fromJson(resStr, resMap.getClass() ) ;
        }else {
            conn.disconnect();
            return null;
        }
    }

    public synchronized static String get(String url, Object parameters){

        StringBuffer sb = new StringBuffer();

        URLConnection con = null;
        OutputStreamWriter osw = null;
        InputStreamReader isr = null;
//        System.out.println("API 호출 : "+url);

        int readTimeout = 60000;
        int connectionTimeout = 60000;

        try{

            con = new URL(url).openConnection();


            con.setConnectTimeout(readTimeout);
            con.setReadTimeout(connectionTimeout);

            if(encoding!=null){
                con.setRequestProperty("Accept-Charset", encoding);
            }

            if(parameters!=null){
                con.setDoOutput(true);
                osw = new OutputStreamWriter(con.getOutputStream());
                osw.write(parameters.toString());
                osw.flush();
            }
            isr = new InputStreamReader(con.getInputStream());
            BufferedReader br = new BufferedReader(isr);

            String tmp = "";
            while((tmp=br.readLine())!=null){
                sb.append(tmp);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{

            if(osw != null){
                try{
                    osw.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            if(isr != null){
                try{
                    isr.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }


}

 

package com.ldh.embed.http;

public class HttpUtilsTest {

    public static void main(String[] args) {
        String returnValue = HttpUtils.get("http://localhost:5000/vectors/나이키", null);
        System.out.println(returnValue);
    }

}

 

확인해보자

GET  http://localhost:5000/vectors/나이키

 

포스트맨에서 이렇게 나오는데

 

 

main 메소드 실행 하여 로그 출력 

 

반응형

'JAVA > java' 카테고리의 다른 글

CommandLineRunner  (2) 2022.03.22
[java] picocli java sample  (0) 2022.03.22
[java] HttpUtils  (0) 2022.01.18
Json 파일 읽기 - json.simple  (0) 2022.01.11
[selenium] 동적생성 웹페이지 크롤링  (0) 2022.01.07
Comments