使用httpClient 调用第三方提供的接口实现发送文件参数
“sendPostFormData”发送post请求方法
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SendRequestUtil {
/**
* 发送post form-data
* @param url
* @param builder
* @return
*/
public static Map<String, Object> sendPostFormData(String url, MultipartEntityBuilder builder) {
//接口推送 封装接口参数
Map<String, Object> result = new HashMap();
CloseableHttpClient httpClient = null;
try {
// 创建 HttpClient 实例
httpClient = HttpClients.createDefault();
// 创建 HttpPost 对象,指定目标 HTTPS URL
HttpPost httpPost = new HttpPost(url);
// 构建表单数据实体
HttpEntity entity = builder.build();
// 将表单数据实体设置到 HttpPost 对象中
httpPost.setEntity(entity);
// 执行 POST 请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
// 检查响应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response status code: " + statusCode);
// 读取响应内容
String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
result = JSON.parseObject(responseBody, Map.class);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭 HttpClient 连接
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
// 创建一个 MultipartEntityBuilder 对象来构建表单数据
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("id", "6fc4d36f0538bd2ce32023de68723b32", ContentType.TEXT_PLAIN);
// 文件参数
File file = new File("path/to/file.txt");
builder.addBinaryBody("file", file, ContentType.TEXT_PLAIN, "file.txt");
//调用发送请求方法
Map<String, Object> result = sendPostFormData("http://127.0.0.1:8080/uploadFile", builder);
System.out.println(result);
}
}