(014) HttpClient上传文件

一、前言

虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

注意: HttpClient有两种形式,一种是org.apache.http下的,一种是org.apache.commons.httpclient.HttpClient。

二、客户端处理
package TestZookeeper.TestZookeeper;

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * 发送请求
 * @author lindm
 * @date 2018/11/30
 */
public class App 
{
    public static void main(String[] args) {
        @SuppressWarnings("deprecation")
        HttpClient ht = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://127.0.0.1:8088/egovAtt/uploadEgovAttFile");
        HttpResponse rs = null;
        try{
            File testFile = new File("C:/Users/Administrator/Documents/Tencent Files/594485991/FileRecv/MobileFile/(批注)(9).pdf");
            System.out.println(testFile.exists());
            //文件流包装到FileBody
            post.setEntity(new InputStreamEntity(new FileInputStream(testFile),testFile.length())); 
            //设置请求内容类型(若不显示设置,默认text/plain;不同的类型服务端解析格式不同,可能导致参请求参数解析不到的情况) 
            post.addHeader("Content-Type", "application/octet-stream"); 
            //设置请求参数docId
            post.addHeader("docId", "W86GOuSwhwKc1xGG");            post.addHeader("type", "pdf");
            //发送请求
            rs = ht.execute(post); 
            System.out.println(""+rs.getStatusLine().getStatusCode()+" "+EntityUtils.toString(rs.getEntity(),"utf-8"));
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            // 销毁
            EntityUtils.consume(rs);
        }
    }

}

三、服务端处理
/**
     * 上传附件,单文件上传<br/>
     * <ul>
     *     <li>请求头需携带参数:docId(所属文档id)、type(附件类别)、contentType(文件类型)
     *     、fileName(附件名称)、Content-Type(文件类型)</li>
     * </ul>
     *
     * @return
     */
    @PostMapping("/uploadEgovAttFileWithFileStream")
    public @ResponseBody String uploadEgovAttFileWithFileStream(HttpServletRequest request) throws Exception {
     
        //从请求头获取参数
        String docId = request.getHeader("docId");
        String type = request.getHeader("type");
        String extension = request.getHeader("extension");
        String fileName = request.getHeader("fileName");

        // 读取文件流
        InputStream is = request.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        is.close();
        // 转为字节数组
        byte[] fileByte = baos.toByteArray();

        //...do anything

        return "upload success";
    }
四、参考博文

1、https://www.cnblogs.com/Scott007/p/3817285.html
2、https://www.cnblogs.com/wuweidong/p/5953167.html
3、https://www.jianshu.com/p/7ab966dfa507

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,908评论 18 139
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,563评论 6 427
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,227评论 25 708
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,041评论 1 3
  • 2017年1 月31日 (西贡) 早起。窗前独坐,沏茶,日记。此住八楼,窗外可见一大片树林,是公园里的。查地图,方...
    左民山人阅读 107评论 0 0