博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过HttpURLConnection 上传文件
阅读量:4080 次
发布时间:2019-05-25

本文共 10914 字,大约阅读时间需要 36 分钟。

参考1:https://www.cnblogs.com/h--d/p/5638092.html

package com.util;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import java.util.Iterator;import java.util.Map;/** * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用, * 但不够简便; *  * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求 * 4.以输入流的形式获取返回内容 5.关闭输入流 *  * @author H__D * */public class HttpConnectionUtil {    /**     * 多文件上传的方法     *      * @param actionUrl:上传的路径     * @param uploadFilePaths:需要上传的文件路径,数组     * @return     */    @SuppressWarnings("finally")    public static String uploadFile(String actionUrl, String[] uploadFilePaths) {        String end = "\r\n";        String twoHyphens = "--";        String boundary = "*****";        DataOutputStream ds = null;        InputStream inputStream = null;        InputStreamReader inputStreamReader = null;        BufferedReader reader = null;        StringBuffer resultBuffer = new StringBuffer();        String tempLine = null;        try {            // 统一资源            URL url = new URL(actionUrl);            // 连接类的父类,抽象类            URLConnection urlConnection = url.openConnection();            // http的连接类            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;            // 设置是否从httpUrlConnection读入,默认情况下是true;            httpURLConnection.setDoInput(true);            // 设置是否向httpUrlConnection输出            httpURLConnection.setDoOutput(true);            // Post 请求不能使用缓存            httpURLConnection.setUseCaches(false);            // 设定请求的方法,默认是GET            httpURLConnection.setRequestMethod("POST");            // 设置字符编码连接参数            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");            // 设置字符编码            httpURLConnection.setRequestProperty("Charset", "UTF-8");            // 设置请求内容类型            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);            // 设置DataOutputStream            ds = new DataOutputStream(httpURLConnection.getOutputStream());            for (int i = 0; i < uploadFilePaths.length; i++) {                String uploadFile = uploadFilePaths[i];                String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);                ds.writeBytes(twoHyphens + boundary + end);                ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename                        + "\"" + end);                ds.writeBytes(end);                FileInputStream fStream = new FileInputStream(uploadFile);                int bufferSize = 1024;                byte[] buffer = new byte[bufferSize];                int length = -1;                while ((length = fStream.read(buffer)) != -1) {                    ds.write(buffer, 0, length);                }                ds.writeBytes(end);                /* close streams */                fStream.close();            }            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);            /* close streams */            ds.flush();            if (httpURLConnection.getResponseCode() >= 300) {                throw new Exception(                        "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());            }            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {                inputStream = httpURLConnection.getInputStream();                inputStreamReader = new InputStreamReader(inputStream);                reader = new BufferedReader(inputStreamReader);                tempLine = null;                resultBuffer = new StringBuffer();                while ((tempLine = reader.readLine()) != null) {                    resultBuffer.append(tempLine);                    resultBuffer.append("\n");                }            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            if (ds != null) {                try {                    ds.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (reader != null) {                try {                    reader.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (inputStreamReader != null) {                try {                    inputStreamReader.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            return resultBuffer.toString();        }    }    public static void main(String[] args) {        // 上传文件测试         String str = uploadFile("http://127.0.0.1:8080/image/image.do",new String[] { "/Users//H__D/Desktop//1.png","//Users/H__D/Desktop/2.png" });         System.out.println(str);    }}uploadFile

参考2:

http://blog.csdn.net/linfeng24/article/details/37885919

private void uploadFile() {          String end = "\r\n";          String twoHyphens = "--";          String boundary = "*****";          String newName = "image.jpg";          String uploadFile = "storage/sdcard1/bagPictures/102.jpg";          ;          String actionUrl = "http://192.168.1.123:8080/upload/servlet/UploadServlet";          try {              URL url = new URL(actionUrl);              HttpURLConnection con = (HttpURLConnection) url.openConnection();              /* 允许Input、Output,不使用Cache */              con.setDoInput(true);              con.setDoOutput(true);              con.setUseCaches(false);              /* 设置传送的method=POST */              con.setRequestMethod("POST");              /* setRequestProperty */              con.setRequestProperty("Connection", "Keep-Alive");              con.setRequestProperty("Charset", "UTF-8");              con.setRequestProperty("Content-Type",                      "multipart/form-data;boundary=" + boundary);              /* 设置DataOutputStream */              DataOutputStream ds = new DataOutputStream(con.getOutputStream());              ds.writeBytes(twoHyphens + boundary + end);              ds.writeBytes("Content-Disposition: form-data; "                      + "name=\"file1\";filename=\"" + newName + "\"" + end);              ds.writeBytes(end);              /* 取得文件的FileInputStream */              FileInputStream fStream = new FileInputStream(uploadFile);              /* 设置每次写入1024bytes */              int bufferSize = 1024;              byte[] buffer = new byte[bufferSize];              int length = -1;              /* 从文件读取数据至缓冲区 */              while ((length = fStream.read(buffer)) != -1) {                  /* 将资料写入DataOutputStream中 */                  ds.write(buffer, 0, length);              }              ds.writeBytes(end);              ds.writeBytes(twoHyphens + boundary + twoHyphens + end);              /* close streams */              fStream.close();              ds.flush();              /* 取得Response内容 */              InputStream is = con.getInputStream();              int ch;              StringBuffer b = new StringBuffer();              while ((ch = is.read()) != -1) {                  b.append((char) ch);              }              /* 将Response显示于Dialog */              showDialog("上传成功" + b.toString().trim());              /* 关闭DataOutputStream */              ds.close();          } catch (Exception e) {              showDialog("上传失败" + e);          }      }

自己:

public static String sendMsg(InputStream fStream) throws Exception {        String wholeUrl = "x";        try {            wholeUrl = "x";            URL object = new URL(wholeUrl);            String end = "\r\n";            String twoHyphens = "--";            String boundary = "*****";            HttpURLConnection con = (HttpURLConnection) object.openConnection();            con.setConnectTimeout(5000);            con.setReadTimeout(30000);            con.setDoInput(true);            con.setDoOutput(true);            con.setUseCaches(false);            con.setRequestMethod("POST");            con.setRequestProperty("Connection", "Keep-Alive");            con.setRequestProperty("Charset", "UTF-8");            con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);            con.setRequestProperty("Accept", "application/json");            DataOutputStream ds = new DataOutputStream(con.getOutputStream());            ds.writeBytes(twoHyphens + boundary + end);            ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"test.jpg\"" + end);            ds.writeBytes(end);         //   FileInputStream fStream = new FileInputStream(file);            int bufferSize = 1024;            byte[] buffer = new byte[bufferSize];            int length = -1;            while ((length = fStream.read(buffer)) != -1) {                ds.write(buffer, 0, length);            }            ds.writeBytes(end);            fStream.close();            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);            LOGGER.info("CardSender start");            ds.flush();            // 显示 POST 请求返回的内容            StringBuilder sb = new StringBuilder();            int HttpResult = con.getResponseCode();            LOGGER.info("CardSender end");            if (HttpResult == HttpURLConnection.HTTP_OK)            {                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));                String line;                while ((line = br.readLine()) != null)                {                    sb.append(line + "\n");                }                br.close();                System.out.println(sb);                return sb.toString();            } else {                LOGGER.error("CardSender.fail " + con.getResponseMessage());                throw new Exception("CardSender.fail " + con.getResponseMessage());            }        } catch (Exception e) {            e.printStackTrace();            LOGGER.error("CardSender.error", e);            throw new Exception("CardSender.error", e);        }    }

为了兼容springmvc的multipartfile,将参数由file改为inputstream
你可能感兴趣的文章
一起来学点redux-saga
查看>>
React 16 加载性能优化指南
查看>>
常见的跨域解决方案(全)
查看>>
《Koa2进阶学习笔记》已完结
查看>>
Koa.js 设计模式-学习笔记
查看>>
Vue经典开源项目汇总
查看>>
leetcode算法练习 JavaScript实现
查看>>
前端面试必备-40道LeetCode经典面试算法题
查看>>
vue更新路由router-view复用组件内容不刷新
查看>>
Jest测试框架入门
查看>>
Jest 断言归纳
查看>>
学习Jest——语法篇
查看>>
charles使用教程
查看>>
前端测试框架Jest系列教程 -- Matchers(匹配器)
查看>>
前端测试框架Jest系列教程 -- Expect(验证)
查看>>
从ES6到ES10的新特性
查看>>
20行代码实现redux,50行代码实现react-redux
查看>>
react hooks 的useCallback hell问题总结
查看>>
useTypescript-React Hooks和TypeScript完全指南
查看>>
service worker的基本知识
查看>>