[Java] 4. Java net - HttpURLConnection Http API 요청


Java net - HttpURLConnection Http API 요청


Java - HttpURLConnection


Java 에서 지원하는 HTTP 관련 기능을 지원하는 URLConnection



Http Post 전송

try {
    JSONObject reqParams = new JSONObject();
    reqParams.put("param1", "data1");
    reqParams.put("param2", "data2");

    URL url = new URL("www.example.com/api/board");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestMethod("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    //Post인 경우 데이터를 OutputStream으로 넘겨 주겠다는 설정
    conn.setDoOutput(true);

    //Request body message에 전송
    OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
    os.write(reqParams.toString());
    os.flush();

    //응답
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    JSONObject jsonObj = (JSONObject)JSONValue.parse(in.readLine());

    //String inputLine;
    //StringBuffer sb = new StringBuffer();
    //while ((inputLine = br.readLine()) != null) {
    //    sb.append(inputLine);
    //}
    br.close();
    in.close();
    conn.disconnect();

} catch(Exception e) {
    e.printStackTrace();
}



Http Get 전송

try {
    URL url = new URL("www.example.com/api/board?param1=data1&param2=data2");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    //데이터를 OutputStream으로 넘겨 주겠다는 설정
    conn.setDoOutput(true);

    //데이터 전송
    OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
    os.write(reqData.toString());
    os.flush();

    //응답
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    JSONObject jsonObj = (JSONObject)JSONValue.parse(in.readLine());

    //String inputLine;
    //StringBuffer sb = new StringBuffer();
    //while ((inputLine = br.readLine()) != null) {
    //    sb.append(inputLine);
    //}
    br.close();
    in.close();
    conn.disconnect();

} catch(Exception e) {
    e.printStackTrace();
}

[참고]

  • https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html