[java] HttpURLConnection - GET/POST

Posted on 2021. 8. 6. 13:23
Filed Under Programming/Java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jettison.json.JSONObject;

//▼HTTP Reqeust GET/POST 샘플 코드
private String charsetName = "UTF-8";

//	Open API 호출 테스트 샘플
public String testGET() throws Exception 
{
	//JSONObject obj = new JSONObject();
	String baseUrl = "http://data.ex.co.kr/openapi/restinfo/restWeatherList?key=0759277880&type=json&sdate=20210507&stdHour=12";	
	String resultJSON = "{}";
	try {
		URL url = new URL(baseUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-type", "text/html; charset="+charsetName);
        
//		conn.setRequestProperty("Authorization", "Basic 암호화한인증키");
//		conn.setRequestProperty("Accept","*/*");
//		conn.setRequestProperty("Accept-Language","ko");
//		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//		conn.setRequestProperty("User-Agent","Mozilla/4.0");
//		conn.setRequestProperty("Host", "서버IP:포트");
//		conn.setRequestProperty("Connection","Keep-Alive");
//		conn.setRequestProperty("Cookie", "바사삭~쿠키");
//		
//		conn.setDoOutput(true);
//		conn.setDoInput(true);
//		conn.setUseCaches(true);        
		
		//conn.setDoInput(true); 
		System.out.println(((HttpURLConnection)conn).getRequestMethod());

//			OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
//			osw.flush();	
		
		int httpResponseCode = conn.getResponseCode();
		BufferedReader rd;
		if(httpResponseCode >= HttpURLConnection.HTTP_OK && httpResponseCode <= HttpURLConnection.HTTP_MULT_CHOICE) {
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), charsetName));
		} else {
			rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), charsetName));
		}
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = rd.readLine()) != null) {
			sb.append(line);
		}
		rd.close();
		conn.disconnect();
		
		resultJSON = sb.toString();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	return resultJSON;
}		

public String testPOST() throws Exception
{
	String baseUrl = "http://my-json-server.typicode.com/smallwitch/apitest/posts";	
	String result = "{}";
	JSONObject jsonObj = new JSONObject();
	try {
		URL url = new URL(baseUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-type", "application/json");
		
		OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), charsetName);
		jsonObj.put("id", 100);
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		jsonObj.put("title", dateFormat.format(date));
		System.out.println("input: "+jsonObj.toString());
		
		osw.write(jsonObj.toString());
		osw.flush();
		
		int httpResponseCode = conn.getResponseCode();
		BufferedReader rd;
		if(httpResponseCode >= HttpURLConnection.HTTP_OK && httpResponseCode <= HttpURLConnection.HTTP_MULT_CHOICE) {
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		} else {
			rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		}
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = rd.readLine()) != null) {
			sb.append(line);
		}
		rd.close();
		conn.disconnect();
		
		result = sb.toString();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	return result;
}

반응형

About

by 쑤기c

반응형