본문 바로가기

프로그래밍 언어/Java

Java) JSON body와 함께 HTTP POST 요청 보내기

1. json body 만들기 

import org.json.simple.JSONObject;
...

public JSONObject createRequestBody(){
    JSONObject body = new JSONObject();

    body.put("key", "value");
    ...

    return body;
}

 

 

2. api 콜하기

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

...


public JSONObject callConversionApi(JSONObject body){
	String apiUrl = "api_url";
    JSONObject result = new JSONObject();
    try{
        HttpURLConnection connection = null;
        URL url = new URL(apiUrl);

        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST"); // post 또는 get, 근데 request body 넣으려면 post!
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", " application/json"); // api 리턴값을 json으로 받을 경우!
        connection.setDoOutput(true);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        bw.write(body.toString());
        bw.flush();
        bw.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));            
        
        // 아래 private 함수 추가 
        result = parseStringToJson(br.readLine());
        
        // 아래 private 함수 추가 
        readResponseCode(connection);

    } catch (ProtocolException e){
        logger.warn(e.getLocalizedMessage());
    } catch (IOException e){
        logger.warn(e.getLocalizedMessage());
    } catch (ParseException e){
        logger.warn(e.getLocalizedMessage());
    }

    return result;
}

 

3. API 결과 JSON으로 파싱하기 

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
...

private JSONObject parseStringToJson(String stringJson) throws ParseException{
    JSONParser parser = new JSONParser();
    Object obj  = parser.parse(stringJson);
    JSONObject json = (JSONObject) obj;
    return json;
}

 

4. API 응답 코드 읽기 

private void readResponseCode(HttpURLConnection connection){

    try{
        int responseCode = connection.getResponseCode();
        if(responseCode == 400){
            System.out.println("400 : command error");
        } else if (responseCode == 500){
            System.out.println("500 : Server error");
        } else {
            System.out.println("response code : " + responseCode);
        }
    } catch (IOException e){
        logger.warn("IOException : read response code error");
    }
}

 


References