[JAVA] HttpURLConnection POST 호출 예제
자바에서 server to server 로 POST 호출하는 코드.
일반 파라미터가 아닌 json 데이터를 실어 보내는 방식은 다음 포스트 참고 : https://blog.naver.com/bb_/222047426772
public String postHttp(String urlString, String parameters, String encoding) throws IOException, Exception { if (encoding == null || encoding.length() == 0) { encoding = “UTF-8”; } HttpURLConnection ucon = null; String result = null; OutputStream os = null; DataOutputStream dos = null; InputStream is = null; try { URL url = new URL(urlString); ucon = (HttpURLConnection) url.openConnection(); ucon.setRequestMethod(“POST”); ucon.setDoOutput(true); ucon.setConnectTimeout(3 * 1000); ucon.setReadTimeout(3 * 1000); ucon.setUseCaches(false); ucon.setRequestProperty(“Accept-Language”, encoding); ucon.setRequestProperty(“connection”, “Keep-Alive”); ucon.setRequestProperty(“cache-control”, “no-cache”); ucon.setRequestMethod(“POST”); os = ucon.getOutputStream(); dos = new DataOutputStream(os); dos.writeBytes(parameters); dos.flush(); dos.close(); int status = ucon.getResponseCode(); if (status >= HttpURLConnection.HTTP_OK || status < HttpURLConnection.HTTP_MULT_CHOICE) { is = ucon.getInputStream(); StringBuffer buf = new StringBuffer(); int c = 0; while ((c = is.read()) != -1) { buf.append((char) c); } result = buf.toString(); result = new String(result.getBytes(“iso-8859-1”)); } ucon.disconnect(); } catch (NullPointerException e) { throw e; } catch (Exception e) { throw e; } finally { try { if (is != null) { is.close(); } } catch (IOException e) { } catch (Exception e) { } try { if (dos != null) { dos.close(); } } catch (IOException e) { } catch (Exception e) { } try { if (os != null) { os.close(); } } catch (IOException e) { } catch (Exception e) { } try { if (ucon != null) { ucon.disconnect(); } } catch (NullPointerException e) { } catch (Exception e) { } } return result; }
|