java使用org.apache.http.client.HttpClient上传文件
时间: 2023-09-01 08:07:37 浏览: 119
HttpClient 文件上传
5星 · 资源好评率100%
以下是一个使用org.apache.http.client.HttpClient上传文件的Java示例:
```java
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class FileUploader {
public static void main(String[] args) {
String url = "http://example.com/upload";
String filePath = "/path/to/file.jpg";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File(filePath));
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println(responseString);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们使用HttpClient创建一个HttpPost请求对象,并使用MultipartEntityBuilder创建一个multipart/form-data实体,以便我们可以将文件作为二进制数据添加到请求中。最后,我们使用execute方法将请求发送到服务器,并从响应中提取响应字符串。
阅读全文