[java] HttpClient를 사용하여 웹 사이트에 PUT 요청을 보내는 방법은?
PUT 요청을 보내기 위해 HttpClient를 사용하는 방법을 알아보겠습니다.
먼저, Apache HttpClient 라이브러리를 프로젝트에 추가해야 합니다. 이를 위해 Maven을 사용한다면 pom.xml 파일에 다음 종속성을 추가해줍니다.
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
이제 HttpClient를 사용하여 PUT 요청을 보내는 코드를 작성해보겠습니다.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class PutRequestExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPut httpPut = new HttpPut("http://www.example.com/put-endpoint");
// 요청 본문에 보낼 데이터를 작성합니다.
String requestBody = "This is the request body.";
HttpEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
httpPut.setEntity(entity);
try {
HttpResponse response = httpClient.execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
// 응답 본문을 확인하고 처리합니다.
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String responseBody = EntityUtils.toString(responseEntity);
System.out.println("Response Body: " + responseBody);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
위 코드에서는 HttpClient를 만들고, PUT 메서드를 사용하여 요청을 보냅니다. 요청 본문에는 “This is the request body.”라는 내용을 포함하고 있습니다.
응답을 받으면 응답 코드와 응답 본문을 확인할 수 있습니다. 이 예제에서는 응답 코드를 출력하고, 응답 본문을 문자열로 변환하여 출력합니다.
위와 같이 HttpClient를 사용하여 PUT 요청을 보낼 수 있습니다.
참고:
- Apache HttpClient: https://hc.apache.org/httpcomponents-client-4.5.x/
- HttpClientBuilder: https://hc.apache.org/httpcomponents-client-4.5.x/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html