[java] HttpClient를 사용하여 파일을 업로드하는 방법은?
- HttpClient 및 HttpPost 객체를 생성합니다.
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/upload");
- MultipartEntityBuilder를 사용하여 업로드할 파일을 설정합니다.
File file = new File("파일 경로");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
HttpEntity multipartEntity = builder.build();
- HttpPost 객체에 MultipartEntity를 설정합니다.
httpPost.setEntity(multipartEntity);
- HttpClient를 사용하여 업로드 요청을 실행합니다.
CloseableHttpResponse response = httpClient.execute(httpPost);
- 업로드 결과를 확인합니다.
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 업로드 성공
} else {
// 업로드 실패
}
전체 코드는 다음과 같습니다:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.File;
import java.io.IOException;
public class FileUploader {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/upload");
File file = new File("파일 경로");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
HttpEntity multipartEntity = builder.build();
httpPost.setEntity(multipartEntity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 업로드 성공
} else {
// 업로드 실패
}
}
}
}
이렇게하면 HttpClient를 사용하여 파일을 업로드할 수 있습니다. 참고로, HttpClient는 Apache HttpComponents 라이브러리의 일부입니다.
참고 자료: