try {
// URL 처리를 위한 URL클래스
String apiURL = "https://search.naver.com/search.naver?&query=날씨";
URL url = new URL(apiURL);
// URL확인
System.out.println("프로토콜 : " + url.getProtocol());
System.out.println("호스트 : " + url.getHost());
System.out.println("파라미터 : " + url.getQuery());
} catch (MalformedURLException e) {
System.out.println("API 주소 오류");
}
→결과
try{
String apiURL = "https://www.naver.com";
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
System.out.println("응답 코드 : " + con.getResponseCode());
System.out.println("정상 : " + HttpURLConnection.HTTP_OK);
System.out.println("Not Found" + HttpURLConnection.HTTP_NOT_FOUND);
System.out.println("Internet Error : " + HttpURLConnection.HTTP_INTERNAL_ERROR);
System.out.println("컨텐트 타입 : " + con.getContentType());
System.out.println("요청 방식 : " +con.getRequestMethod());
con.disconnect(); // 접속 해제 (생략 가능)
} catch (MalformedURLException e) { // URL 클래스
System.out.println("API 주소 오류");
} catch (IOException e) { // HttpURLConnection 클래스
}
try{
String apiURL = "https://www.naver.com";
URL url = new URL (apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// 바이트 입력 스트림
InputStream in = con.getInputStream();
// 문자 입력 스트림으로 변환
InputStreamReader reader = new InputStreamReader(in);
// 모두 읽어서 StringBuilder에 저장
StringBuilder b = new StringBuilder();
char[] cbuf = new char[100]; // 100글자씩 처리
int readCnt = 0; // 실제로 읽은 글자 수
while((readCnt = reader.read(cbuf)) != -1) {
sb.append(cbuf, 0 ,readCnt);
}
// StringBuilder의 모든 내용을 C:\\storage\\naver.html로 내보내기
File file = new File("C:\\storage", "naver.html");
FileWriter fw = new FileWriter(file);
fw.write(sb.toString());
fw.close();
reader.close();
con.disconnect();
} catch (MalformedURLException e) {
System.out.println("API 주소 오류");
} catch (IOException e) {
System.out.println("API 접속 및 연결 오류");
}
try{
// 접속
String apiURL = "https://kma.go.kr/XML/weather/sfc_web_map.xml";
URL url = new URL(apiURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// 접속 확인 코드
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("API 접속 실패");
return;
}
// 바이트 입력 스트림 → 문자 입력 스트림 → 버퍼 추가
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
File file = new File("C:\\storage", "sfc_web_map.xml");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
// readLine() 메소드를 이용한 복사
String line = null;
while((line = br.readLine()) != null) {
bw.write(line + "\n");
}
// 닫기
bw.close();
br.close();
con.disconnect();
} catch (MalformedURLException e) {
System.out.println("API 주소 오류");
} catch (IOException e) {
System.out.println("API 서버 오류");
}
try {
// 원본데이터
String str = "한글 english 12345 !@#$+";
// 인코딩
String encode = URLEncoder.encode(str, "UTF-8");
System.out.println(encode);
// 디코딩
String decode = URLDecoder.decode(encode, StandardCharsets.UTF_8);
System.out.println(decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
→ 결과
인코딩 : %ED%95%9C%EA%B8%80+english+12345+%21%40%23%24%2B
디코딩 : 한글 english 12345 !@#$+
package ex02_api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class Main2 {
// 요청
// 1. Request
// 2. 클라이언트 -> 서버
// 파라미터
// 1. Parameter
// 2. 보내는 데이터(변수 개념)
// 응답
// 1. Response
// 2. 서버 -> 클라이언트
public static void m1() {
// 전국종량제봉투가격표준데이터
// API 주소 (주소 + 요청 파라미터)
String apiURL = "http://api.data.go.kr/openapi/tn_pubr_public_weighted_envlp_api";
try {
String serviceKey = "bEQBRPHjt0tZrc7EsL0T8usfsZ1+wT+5jqamBef/ErC/5ZO6N7nYdRmrwR91bh5d3I1AQeY5qdbJOF6Kv0U1CQ==";
apiURL += "?pageNo=" + URLEncoder.encode("0", "UTF-8");
apiURL += "&numOfRows=" + URLEncoder.encode("100", "UTF-8");
apiURL += "&type=" + URLEncoder.encode("xml", "UTF-8");
apiURL += "&CTPRVN_NM=" + URLEncoder.encode("인천광역시", "UTF-8");
apiURL += "&SIGNGU_NM=" + URLEncoder.encode("계양구", "UTF-8");
apiURL += "&WEIGHTED_ENVLP_TYPE=" + URLEncoder.encode("규격봉투", "UTF-8");
apiURL += "&WEIGHTED_ENVLP_MTHD=" + URLEncoder.encode("소각용", "UTF-8");
apiURL += "&WEIGHTED_ENVLP_PRPOS=" + URLEncoder.encode("생활쓰레기", "UTF-8");
apiURL += "&WEIGHTED_ENVLP_TRGET=" + URLEncoder.encode("기타", "UTF-8");
apiURL += "&serviceKey=" + URLEncoder.encode(serviceKey, "UTF-8");
} catch(UnsupportedEncodingException e) {
System.out.println("인코딩 실패");
}
// API 주소 접속
URL url = null;
HttpURLConnection con = null;
try {
url = new URL(apiURL);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");
} catch(MalformedURLException e) {
System.out.println("API 주소 오류");
} catch(IOException e) {
System.out.println("API 주소 접속 실패");
}
// 입력 스트림(응답) 생성
// 1. 응답 성공 시 정상 스트림, 실패 시 에러 스트림
// 2. 응답 데이터는 StringBuilder에 저장
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String line = null;
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// 스트림 종료
reader.close();
} catch(IOException e) {
System.out.println("API 응답 실패");
}
String response = sb.toString();
System.out.println(response);
// 접속 종료
con.disconnect();
}
public static void main(String[] args) {
m1();
}
}