HttpURLConnection上传文件,下载文件

  • Post author:
  • Post category:其他


HttpURLConnection上传文件,下载文件



上传文件

1:controller层

    @RequestMapping("/uploadFrImage")
    @ResponseBody
    public JSONObject uploadFrImage(@RequestParam MultipartFile[] files,String uuid, String security,String industry) {
        try {
            String urlStr = "localhost:8080/xxx/uploadFrImage";
            String url = baseUrl+urlStr;
            Map strParams = new HashMap();
            strParams.put("uuid",uuid);
            strParams.put("security",security);
            strParams.put("industry",industry);
            Map<String,InputStream> fileParams = new HashMap<>();
            for(int i=0;i<files.length;i++){
                fileParams.put(files[i].getOriginalFilename(),files[i].getInputStream());
            }
            String str = fasCommonService.uploadFile(url,strParams,fileParams);
            return JSON.parseObject(str);
        } catch (Exception e) {
            logger.error("startOcr Exception [{}]", e.getMessage());
            return null;
        }
    }

2:service层

    //换行
    private static final String LINE_END = "\r\n";
    // 前缀
    private static final String PREFIX = "--";
    // 边界标识 随机生成
    private static final String BOUNDARY = UUID.randomUUID().toString();
    // 编码格式
    private static final String CHARSET = "utf-8";
    // 数据类型
    private static final String CONTENT_TYPE = "multipart/form-data";
    // 超时时间
    private static final int TIME_OUT = 20 * 1000;

    private HttpURLConnection getHttpURLConnection(String actionUrl){
        HttpURLConnection httpURLConnection = null;
        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // http的连接类
            httpURLConnection =(HttpURLConnection) url.openConnection();
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 读取时间
            httpURLConnection.setReadTimeout(TIME_OUT);
            // 连接时间
            httpURLConnection.setConnectTimeout(TIME_OUT);
            // 设置请求头参数
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return httpURLConnection;
    }

    /**
     * 上传文件
     * @param actionUrl
     * @param strParams
     * @param fileParams 文件名/文件
     * @return
     */
    public String uploadFile(String actionUrl,Map strParams,Map<String, InputStream> fileParams) {
        DataOutputStream dos = null;
        InputStream in = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        HttpURLConnection httpURLConnection = null;
        StringBuilder response = null;
        try {
            httpURLConnection = getHttpURLConnection(actionUrl);
            // 请求体,上传参数
            dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // str 参数
            dos.writeBytes(getStrParams(strParams).toString());
            dos.flush();
            // 文件上传
            StringBuilder fileSb = new StringBuilder();
            for (Map.Entry<String, InputStream> fileEntry: fileParams.entrySet()){
                fileSb.append(PREFIX)
                       .append(BOUNDARY)
                       .append(LINE_END)
                        /**
                         * 这里重点注意: name里面的值为服务端需要的key 只有这个key 才可以得到对应的文件
                         * filename是文件的名字,包含后缀名的 比如:abc.png
                         */
                        .append("Content-Disposition: form-data; name=\"files\"; filename=\""
                                + fileEntry.getKey() + "\"" + LINE_END)
    //   .append("Content-Type: image/jpg" + LINE_END) //此处的ContentType不同于 请求头中Content-Type
    //   .append("Content-Transfer-Encoding: 8bit" + LINE_END)
                        .append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
                dos.writeBytes(fileSb.toString());
                dos.flush();
                InputStream is = fileEntry.getValue();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1){
                    dos.write(buffer,0,len);
                }
                is.close();
                dos.writeBytes(LINE_END);
            }
            //请求结束标志
            dos.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
            dos.flush();
            //读取服务器返回信息
            if (httpURLConnection.getResponseCode() == 200) {
                in = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(in);
                reader = new BufferedReader(inputStreamReader);
                String line = null;
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
            if (dos!=null){
                try{
                    dos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if(reader !=null){
                try{
                    reader.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 对post参数进行编码处理
     * */
    private StringBuilder getStrParams(Map<String,String> strParams){
        StringBuilder strSb = new StringBuilder();
        for (Map.Entry<String, String> entry : strParams.entrySet()){
            strSb.append(PREFIX)
                    .append(BOUNDARY)
                    .append(LINE_END)
                    .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END)
                    .append("Content-Type: text/plain; charset=" + CHARSET + LINE_END)
                    .append("Content-Transfer-Encoding: 8bit" + LINE_END)
                    // 参数头设置完以后需要两个换行,然后才是参数内容
                    .append(LINE_END)
                    .append(entry.getValue())
                    .append(LINE_END);
        }
        return strSb;
    }



下载文件

1:controller层

    @RequestMapping(value = "/getFrOcrMatchResultForExcel", method = RequestMethod.GET)
    @ResponseBody
    public void getFrOcrMatchResultForExcel(String objects, String fileType, String security, HttpServletResponse response) throws Exception {
        String urlStr = "localhost:8080/getFrOcrMatchResultForExcel?security="+security+"&objects="+objects+"&fileType="+fileType;
        fasCommonService.downloadFile(baseUrl+urlStr,response);
    }

1:service层

 public void downloadFile(String urlPath, HttpServletResponse response) {
       try {
           // 统一资源
           URL url = new URL(urlPath);
           // 连接类
           HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
           // 设定请求的方法,默认是GET
           httpURLConnection.setRequestMethod("GET");
           // 设置字符编码
           httpURLConnection.setRequestProperty("Charset", "UTF-8");
           // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
           httpURLConnection.connect();
           if (httpURLConnection.getResponseCode() == 200) {
               OutputStream os = response.getOutputStream();
               BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
               String contentDispositionStr = httpURLConnection.getHeaderField("Content-Disposition");
               String fileName = contentDispositionStr.substring(contentDispositionStr.lastIndexOf("=")+1);
               response.reset();
               response.setHeader("Content-Disposition", "attachment; filename="+ fileName);
               String fileExt = FileUtil.getFileExt(fileName);
               if(IConstants.OCR_FILE_TYPE_XLSX.equalsIgnoreCase(fileExt) || IConstants.OCR_FILE_TYPE_XLS.equalsIgnoreCase(fileExt)){
                   response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
               } else if(IConstants.OCR_FILE_TYPE_PDF.equalsIgnoreCase(fileExt)){
                   response.setContentType("application/pdf;charset=utf-8");
               }else {
                   response.setContentType("application/octet-stream; charset=gbk");
               }
//                file = new File("C:\\Users\\lx\\Desktop\\test1\\bb\\"+fileName);
//                OutputStream out = new FileOutputStream(file);
               int size = 0;
               byte[] buf = new byte[1024];
               while ((size = bin.read(buf)) != -1) {
                   os.write(buf, 0, size);
               }
               os.flush();
               os.close();
               bin.close();
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }



POST 请求

public String doPost(String urlStr, Map params) {
        URL connect;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            // 读取时间
            connection.setReadTimeout(TIME_OUT);
            // 连接时间
            connection.setConnectTimeout(TIME_OUT);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("accept", "application/json, text/plain, */*");
            connection.setRequestProperty("connection", "keep-alive");
            connection.setRequestProperty("user-agent", "");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36");
            OutputStreamWriter paramout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            String paramsStr = "";
            for (Object param : params.keySet()) {
                paramsStr += "&" + param + "=" + params.get(param);
            }
            if (!paramsStr.isEmpty()) {
                paramsStr = paramsStr.substring(1);
            }
            paramout.write(paramsStr);
            paramout.flush();
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    data.append(line);
                }
                reader.close();
            }
            paramout.close();

            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data.toString();
    }



版权声明:本文为weixin_40263855原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。