코딩마을방범대
[Java] HttpURLConnection 통해서 사이트 접속 후 응답받기 본문
728x90
HttpURLConnection
Java에서 HTTP 프로토콜을 사용하여 웹 리소스에 접근하고 통신하기 위한 클래스
호출하고 응답받기
public void test throws IOException {
URL url = new URL("http://javaking75.blog.me/rss");
// 문자열로 URL 표현
System.out.println("URL :" + url.toExternalForm());
// HTTP Connection 구하기
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 요청 방식 설정 ( GET or POST or .. 별도로 설정하지않으면 GET 방식 )
conn.setRequestMethod("GET");
// 연결 타임아웃 설정
conn.setConnectTimeout(3000); // 3초
// 읽기 타임아웃 설정
conn.setReadTimeout(3000); // 3초
// 응답 헤더의 정보를 모두 출력
for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
for (String value : header.getValue()) {
System.out.println(header.getKey() + " : " + value);
}
}
// 응답 코드 확인
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 응답 데이터 읽기
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} else {
System.out.println("HTTP 요청 실패: " + responseCode);
}
// 접속 해제
conn.disconnect();
}
HttpURLConnection의 메소드
※ 아래 메소드들을 사용할 경우 따로 connection() 메소드를 선언해주지 않아도 됨!
( * 는 위의 예시에 포함되어 있음)
메소드 | 설명 |
getRequestMethod | 요청 방식 ( GET, POST 등 ... ) |
getContentType | 응답 콘텐츠 유형 ( text/html; charset=UTF-8 등 ...) |
getResponseCode | 응답 코드 ( 200, 404 등 ... ) |
getResponseMessage | 응답 메시지 ( OK, Not Found 등 ... ) |
*getHeaderFields |
응답 헤더 정보들 |
*getInputStream |
응답 데이터 ( Response Data 를 리턴 ) |
POST API에 Request 값 보내기
public static void main(String[] args) {
try {
// 웹 서버 URL 설정
URL url = new URL("https://example.com/api");
// HttpURLConnection 객체 생성
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// HTTP POST 요청 설정
conn.setRequestMethod("POST");
conn.setDoOutput(true); // POST 데이터를 보낼 것이므로 출력을 허용
/**
*
* !!!!!! request 타입이 json 형태인지 text 형태인지에 따라 아래 코드 참고하여 여기에 넣기!!!!!!!!!
*
**/
// 응답 코드 확인
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 응답 데이터 읽기
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} else {
System.out.println("HTTP 요청 실패: " + responseCode);
}
// 연결 종료
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
setDoOutput 란?
conn.setDoOutput(true) 은 HttpURLConnection 객체를 사용하여 HTTP 요청을 보낼 때 출력 스트림을 사용할 것인지 여부를 결정하는 메소드이다.
기본적으로 HttpURLConnection 은 입력 스트림을 사용하기 위해 설정되어 있으며,
setDoOutput을 사용해 출력 스트림을 사용하도록 설정하면 요청 본문에 데이터를 기입할 수 있다.
setDoOutput(true)를 호출한 뒤에는 getOutputStream() 메소드를 사용해 출력 스트림을 얻을 수 있다.
1. text 형식의 request
// POST 데이터 설정
String postData = "param1=value1¶m2=value2"; // 원하는 데이터를 문자열로 설정
byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
// 요청 본문에 데이터 작성
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postDataBytes);
}
2. json 형식의 request
// JSON 데이터 생성
String jsonInputString = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
// Content-Type 헤더 설정
conn.setRequestProperty("Content-Type", "application/json; utf-8");
// 요청 본문에 JSON 데이터 작성
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
byte[] jsonInputBytes = jsonInputString.getBytes(StandardCharsets.UTF_8);
wr.write(jsonInputBytes);
}
참고사이트
[Java] HttpURLConnection 클래스 - URL 요청후 응답받기 ( GET방식, POST방식 )
728x90
'💡 백엔드 > Java' 카테고리의 다른 글
[java] ProGuard를 이용하여 war파일 난독화하기 (0) | 2023.11.23 |
---|---|
[JAVA] 서버에서 웹소켓 세션 종료하기 (0) | 2023.11.20 |
Java Quartz를 이용해 동적 스케줄링 설정하기 (0) | 2023.10.04 |
[Java] @Transactional 에 대해서 (& 프록시객체) (0) | 2023.08.04 |
순차 & 병렬 & 병행 처리의 차이점과 Java의 stream & parallelStream (0) | 2023.08.01 |