java、 http模拟post上传文件到服务端 模拟form上传文件
2018-03-08 10:46
513 查看
需求是这样的:
**1,前后端分离,前端对接pc软件进行文件同步的接口,后的springboot微服务进行文件接收和处理。
2,软件不能直接调用微服务的接口进行上传,只能先走一下前端controller进行转发过来()。
3,这样就只能用httpclient进行http的转发请求,先把文件上传来放到本地临时处理下,在转到微服务端进行处理。
4,post方式传输,单纯的字符参数好处理,单纯的文件也能处理,2个都存在,会有一些小问题,尤其是报文那里。**
第一步:同步文件的接口
第二部:模拟post传输工具类
第三部:服务接收端 处理文件file
**1,前后端分离,前端对接pc软件进行文件同步的接口,后的springboot微服务进行文件接收和处理。
2,软件不能直接调用微服务的接口进行上传,只能先走一下前端controller进行转发过来()。
3,这样就只能用httpclient进行http的转发请求,先把文件上传来放到本地临时处理下,在转到微服务端进行处理。
4,post方式传输,单纯的字符参数好处理,单纯的文件也能处理,2个都存在,会有一些小问题,尤其是报文那里。**
第一步:同步文件的接口
@ResponseBody @RequestMapping(value="/res/upload",method=RequestMethod.POST, produces = "text/html;charset=UTF-8") public String softUpload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { MultipartFile dataFile = request.getFile("file"); String userName = request.getParameter("userName"); String token = request.getParameter("token"); String fileName = dataFile.getOriginalFilename(); String ext = fileName.substring(fileName.lastIndexOf(".")); String saveFileName = ""; String relativePath = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); relativePath = sdf.format(new Date()) + File.separator + UUID.randomUUID().toString().replace("-", ""); saveFileName = Configuration.getDataPath() + "/" + relativePath + ext; // 将文件保存起来 FileUtils.writeByteArrayToFile(new File(saveFileName), dataFile.getBytes()); String doPost = HttpUtils.doPostWithFile(url, saveFileName,fileName,userName); return doPost; }
第二部:模拟post传输工具类
/** * 提交file模拟form表单 * @param url * @param savefileName * @param fileName * @param param * @return */ public static String doPostWithFile(String url,String savefileName,String fileName, String param) { String result = ""; try { // 换行符 final String newLine = "\r\n"; final String boundaryPrefix = "--"; // 定义数据分隔线 String BOUNDARY = "========7d4a6d158c9"; // 服务器的域名 URL realurl = new URL(url); // 发送POST请求必须设置如下两行 HttpURLConnection connection = (HttpURLConnection) realurl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection","Keep-Alive"); connection.setRequestProperty("Charset","UTF-8"); connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY); // 头 String boundary = BOUNDARY; // 传输内容 StringBuffer contentBody =new StringBuffer("--" + BOUNDARY); // 尾 String endBoundary ="\r\n--" + boundary + "--\r\n"; // 1. 处理普通表单域(即形如key = value对)的POST请求(这里也可以循环处理多个字段,或直接给json) //这里看过其他的资料,都没有尝试成功是因为下面多给了个Content-Type //form-data 这个是form上传 可以模拟任何类型 contentBody.append("\r\n") .append("Content-Disposition: form-data; name=\"") .append("param" + "\"") .append("\r\n") .append("\r\n") .append(param) .append("\r\n") .append("--") .append(boundary); String boundaryMessage1 =contentBody.toString(); System.out.println(boundaryMessage1); out.write(boundaryMessage1.getBytes("utf-8")); // 2. 处理file文件的POST请求(多个file可以循环处理) contentBody = new StringBuffer(); contentBody.append("\r\n") .append("Content-Disposition:form-data; name=\"") .append("file" +"\"; ") // form中field的名称 .append("filename=\"") .append(fileName +"\"") //上传文件的文件名,包括目录 .append("\r\n") .append("Content-Type:multipart/form-data") .append("\r\n\r\n"); String boundaryMessage2 = contentBody.toString(); System.out.println(boundaryMessage2); out.write(boundaryMessage2.getBytes("utf-8")); // 开始真正向服务器写文件 File file = new File(savefileName); DataInputStream dis= new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut =new byte[(int) file.length()]; bytes =dis.read(bufferOut); out.write(bufferOut,0, bytes); dis.close(); byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 4. 从服务器获得回答的内容 String strLine=""; String strResponse =""; InputStream in =connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while((strLine =reader.readLine()) != null) { strResponse +=strLine +"\n"; } System.out.print(strResponse); return strResponse; } catch (Exception e) { System.out.println("发送POST请求出现异常!" + e); e.printStackTrace(); } return result; }
第三部:服务接收端 处理文件file
//新建资源这个是springboot接口 @RequestMapping(value = "/upload",method =RequestMethod.POST) public ReturnResult<?> uploadRes( MultipartFile file, String param)throws Exception; //这里@RequestPart 注解直接接受file就可以了 public ReturnResult<?> uploadRes(@RequestPart("file") MultipartFile file,@RequestParam("param") String name) throws Exception{ logger.info("****新建资源****"); //处理逻辑 }
相关文章推荐
- 使用java的HttpURLconnnection模拟form上传 以及apache httpClient 直接上传文件
- httpurlconnection模拟post提交form表单(普通文本和上传文件) (
- httpClient4.3 模拟Post提交,模拟Post上传文件并解决服务端使用spingMVC时upload.parseRequest(request)解析不到File,Pos简单抓取页面数据
- httpclient通过POST来上传文件,而不是通过流的形式,并在服务端进行解析(通过httpmime.jar来操作)
- java中使用scoket模拟http post请求发送图片或文件
- HttpClient PostMethod模拟带文件上传+普通字段的http请求(可解决文件为网络文件的问题)
- java中使用scoket模拟http post请求发送图片或文件
- android 上传文件"Content-Type",为"application/octet-stream" 用php程序在服务端用$GLOBALS['HTTP_RAW_POST_DATA']接受(二)
- HTTP POST请求报文格式分析与Java实现文件上传
- java模拟post请求上传文件
- java中使用scoket模拟http post请求发送图片或文件
- HTTP POST请求报文格式分析与Java实现文件上传
- httpclient通过POST来上传文件,而不是通过流的形式,并在服务端进行解析(通过httpmime.jar来操作)
- Java客户端通过Http发送POST请求上传文件到web服务器
- android向服务器上传multipart/form-data文件(upload using multipart post using httpclient in android)
- httpclient通过POST来上传文件,而不是通过流的形式,并在服务端进行解析(通过httpmime.jar来操作)
- JAVA_模拟HTTP表单POST文本或文件
- java中使用scoket模拟http post请求发送图片或文件
- httpclient通过POST来上传文件,而不是通过流的形式,并在服务端进行解析(通过httpmime.jar来操作)
- Java利用HttpURLConnection发送post请求上传文件