其他分享
首页 > 其他分享> > httpClient发送文件

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();
    }
原文链接:https://blog.csdn.net/qq_43571415/article/details/100737810

标签:文件,HttpEntity,String,uploadFile,builder,发送,new,httpClient
来源: https://www.cnblogs.com/lzy7422/p/14816521.html