Java调用post 上传文件带参
时间: 2023-08-04 07:14:37 浏览: 94
Java调用post上传文件带参可以使用Apache HttpComponents库来实现,具体步骤如下:
1. 引入HttpComponents库
```java
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
```
2. 创建HttpPost请求
```java
HttpPost httpPost = new HttpPost(url);
```
3. 创建MultipartEntityBuilder
```java
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
```
4. 添加文件参数
```java
builder.addBinaryBody("file", file);
```
5. 添加其他参数
```java
builder.addTextBody("param1", "value1");
```
6. 构建HttpEntity
```java
HttpEntity entity = builder.build();
```
7. 设置请求实体
```java
httpPost.setEntity(entity);
```
8. 执行请求
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
```
完整代码示例:
```java
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public class HttpUpload {
public static void main(String[] args) {
String url = "http://localhost:8080/upload";
File file = new File("test.txt");
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file);
builder.addTextBody("param1", "value1");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
System.out.println(EntityUtils.toString(responseEntity));
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文