Study/Java

Http post(s) example

LoonyHyun 2020. 12. 9. 13:13
반응형

참고 : docs.oracle.com/javase/7/docs/api/javax/net/ssl/HttpsURLConnection.html

 

HttpsURLConnection (Java Platform SE 7 )

Returns the server's principal which was established as part of defining the session. Note: Subclasses should override this method. If not overridden, it will default to returning the X500Principal of the server's end-entity certificate for certificate-bas

docs.oracle.com

 

(코드 예시)

 

int TIMEOUT_VALUE = 5000;

String SEND_URL = "";
String PARAMS = "";

URL url = null;
HttpsURLConnection con = null;

try {
	url = new URL(SEND_URL);
	con = (HttpsURLConnection) url.openConnection();
	//SEND_URL이 http 인 경우 HttpURLConnection
	//SEND_URL이 https 인 경우 HttpsURLConnection
    
	con.setDoInput(true);  //URLConnection 에 대한 doInput 플래그 : default true
	con.setDoOutput(true); //URLConnection 에 대한 doOutput 플래그 : default false
	
	con.setRequestMethod("POST");
	
	con.setRequestProperty("User-Agent", USER_AGENT);
	con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
	
	con.setConnectTimeout(TIMEOUT_VALUE);
	con.setReadTimeout(TIMEOUT_VALUE);

	// Send post request
	OutputStream os = con.getOutputStream();
	os.write(PARAMS.getBytes());
	os.flush();

	int responseCode = con.getResponseCode();
	System.out.println(responseCode);
	
	BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();
	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();
	os.close();
    
	System.out.println(response.toString());
	
} catch (MalformedURLException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} catch (Exception e) {
	e.printStackTrace();
} finally {
	
}