java实现HttpClient上传文件

  • 控制器
public String dataPicAdd( @RequestParam(value = "img",required = false) MultipartFile uploadImage,
                             Model model)  throws Exception{
	String sTestsetFile=facePath;
    String sURL="https://www.baidu.com";
    //CloseableHttpClient意思是:可关闭的
    CloseableHttpClient httpClient = HttpClients.createDefault();//1、创建实例
    HttpPost uploadFile = new HttpPost(sURL);//2、创建请求
    
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("text", "111", ContentType.TEXT_PLAIN);//传参
    builder.setCharset(Charset.forName("utf8"));//设置请求的编码格式
    //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
    
    // 把文件加到HTTP的post请求中
    File f = new File(sTestsetFile);
    builder.addBinaryBody(
            "img",
            new FileInputStream(f),
            ContentType.APPLICATION_OCTET_STREAM,
            f.getName()
    );

    HttpEntity multipart = builder.build();
    uploadFile.setEntity(multipart);//对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
    CloseableHttpResponse response = httpClient.execute(uploadFile);//3、执行
    HttpEntity responseEntity = response.getEntity();//4、获取实体

    Header header=responseEntity.getContentType();
    //打印内容
    String sResponse= EntityUtils.toString(responseEntity, "UTF-8");//5、获取网页内容,并且指定编码
    System.out.println("Post 返回结果"+sResponse);
    httpClient.close();
    response.close();
    }
  • maven
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3.6</version>
</dependency>

小白一枚,遇到问题,欢迎评论

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值