Http 통신하기 Apache HttpClient 사용

2024. 10. 19. 13:45Java

pom.xml

<dependency>
	<groupId>org.apache.httpcomponents.client5</groupId>
	<artifactId>httpclient5</artifactId>
	<version>5.1</version>
</dependency>

GET 방식

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // Create a GET request
            HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");

            // Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response: " + responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

POST 방식

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;

public class HttpClientPostExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // Create a POST request
            HttpPost post = new HttpPost("https://jsonplaceholder.typicode.com/posts");

            // Set request headers
            post.setHeader("Content-Type", "application/json");

            // Set JSON body
            String json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
            post.setEntity(new StringEntity(json));

            // Execute the request
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                System.out.println("Response: " + response.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

'Java' 카테고리의 다른 글

Recursive 파일 정보 가져오기  (0) 2024.11.06
String "2024-11-06 11:24:01 +0900"을 Date로 변환  (1) 2024.11.06
String[]을 List로 전환  (0) 2024.09.08
String 배열에 요소 추가  (0) 2024.08.28
nslookup 구현  (0) 2024.08.23