HttpsURLConnection, HttpURLConnection – GET / POST

HttpsURLConnection, HttpURLConnection – GET / POST

GET

HttpsURLConnection conn = null;
String resultJSON = "";
URL url;

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
try {
    StringBuffer params = new StringBuffer();
    params.append("param1=" + value);
    params.append("&param2=" + value2);
    
    url = new URL(apiUrl + "?" + params.toString());
    
    conn = (HttpsURLConnection) url.openConnection();
        
    if(conn != null) {              
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        conn.setRequestMethod("GET");
        conn.setDefaultUseCaches(false);
                
        conn.connect();
            
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String input = null;
                            
        while ((input = br.readLine()) != null){
            resultJSON += input;
        }
        br.close();
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

POST

HttpsURLConnection conn = null;
String resultJSON = "";
URL url;

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
try {
    StringBuffer params = new StringBuffer();
    params.append("param1=" + value);
    params.append("&param2=" + value2);
    
    url = new URL(apiUrl);
    
    conn = (HttpsURLConnection) url.openConnection();
        
    if(conn != null) {              
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        conn.setRequestMethod("GET");
        conn.setDefaultUseCaches(false);
        // post
        conn.setDoOutput(true);

        // parameter 전송
        if(conn.getDoOutput()) {
            conn.getOutputStream().write(params.toString().getBytes());
            conn.getOutputStream().flush();
            conn.getOutputStream().close();
        }
            
        conn.connect();
            
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String input = null;
                            
        while ((input = br.readLine()) != null){
            resultJSON += input;
        }
        br.close();
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

One comment

  1. 멋쪄요 선물로 도토리 두고가여…(뒤적뒤적) 도토리가 없어서 밤 3개 두고가여
    ()
    – –

    응답

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다