通过apache-httpclient上传文件可以通过以下步骤实现:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://example.com/upload");
File file = new File("path/to/file");
FileBody fileBody = new FileBody(file);
HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
完整的示例代码如下:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public class FileUploadExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://example.com/upload");
File file = new File("path/to/file");
FileBody fileBody = new FileBody(file);
HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();
httpPost.setEntity(entity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Status Code: " + statusCode);
System.out.println("Response Body: " + responseBody);
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意,以上示例代码仅为演示如何使用Apache HttpClient上传文件,实际应用中可能需要根据具体情况进行适当的修改和异常处理。
领取专属 10元无门槛券
手把手带您无忧上云