8.14Java之使用HttpClient类通过POST方式上传文件

8.14Java之使用HttpClient类通过POST方式上传文件

背景

简介:

因为在实际的业务当中存在上传文件的场景。经常是通过ajax发送form-data形式的表单。所以在测试的时候需要构造表单的形式进行测试。

关键参数

  • Content-Type:multipart/form-data;

  • 参数:file二进制类型

构造实例:
package AmazonListingAPI;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

/**
* 测试Amazon上传图片的API
* @since JDK 1.8
* @date 2021/08/14
* @author Lucifer
*/
public class UploadFileAPITestNo2 {
   //设置文件路径
   private static File filePath = new File("C:\\Users\\Administrator\\Desktop\\Test_Work\\Test_Picture\\King.jpg");
   public static void uploadFile(String url, String cookValue){
       //设置Cookie
       CookieStore cookieStore = new BasicCookieStore();
       BasicClientCookie cookie = new BasicClientCookie("Cookie", cookValue);
       try {
           cookie.setDomain(new URL(url).getHost());
      } catch (MalformedURLException e) {
           e.printStackTrace();
      }
       cookie.setPath("/");
       cookieStore.addCookie(cookie);
       CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

       String result = "";
       //每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
       String boundary ="----WebKitFormBoundary0j3qBlYRoC96tFB3";
       try {
           //文件名
           String fileName = filePath.getName();
           HttpPost httpPost = new HttpPost(url);
           //设置请求头
           httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);

           //HttpEntity builder
           MultipartEntityBuilder builder = MultipartEntityBuilder.create();
           //字符编码
           builder.setCharset(Charset.forName("UTF-8"));
           //模拟浏览器
           builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
           //boundary
           builder.setBoundary(boundary);
           //multipart/form-data
           builder.addPart("multipartFile",new FileBody(filePath));
           // binary
//           builder.addBinaryBody("name=\"multipartFile\"; filename=\"test.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
//           //其他参数
//           builder.addTextBody("filename", fileName, ContentType.create("text/plain", Consts.UTF_8));
           //HttpEntity
           HttpEntity entity = builder.build();
           httpPost.setEntity(entity);
           // 执行提交
           HttpResponse response = httpClient.execute(httpPost);
           //响应
           HttpEntity responseEntity = response.getEntity();
           if (responseEntity != null) {
               // 将响应内容转换为字符串
               result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
          }
      } catch (IOException e) {
           e.printStackTrace();
      } catch (Exception e) {
           e.printStackTrace();
      } finally {
           try {
               httpClient.close();
          } catch (IOException e) {
               e.printStackTrace();
          }
      }
       System.err.println("result"+result);
//       return result;
  }

   public static void main(String[] args) {
       uploadFile();
  }
}

调用方法只需要传url和cookie即可,有需要可以把FIle对象作为形参

posted @   俊king  阅读(1703)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示