HttpClient发送文件与报文
2016-05-19 15:47
441 查看
1、入口。
用于组装报文加密等操作。/** * * @author cgw * @date 2016-05-04 * * @Title httpPost 传输文件与报文 (主要用于每日身份证照片上传给民生银行) * @param requestUrl 请求地址 * @param requestName 请求报文名(一般为certinfo) * @param request 报文信息 * @param requestFileName 请求文件名 (一般为cert) * @param filePath 文件路径 * @param fileName 文件名 * @param funcNo 交易号 * @param type 类型 * @return */ public static Map<String, Object> httpPost(String requestUrl,String requestName, Map<String, Object> request, String requestFileName, String filePath, String fileName, EnumCMBCFuncNo funcNo, int type) { Map<String, Object> res = new HashMap<String, Object>(); try { File file = new File(filePath); String requestStr = doSignPass(request, funcNo); HttpResult result = HttpHelper.post(requestUrl, requestName, requestStr, requestFileName, file, fileName, ENCODING, HS_SO_TIMEOUT, new BasicCookieStore()); if (null != result) { int statusCode = result.getStatuCode(); if (statusCode == 200) { String responseStr = result.getHtml(); res = doUnSignPass(funcNo.getFuncNo(), responseStr, type); } } } catch (Exception e) { logger.error("http post请求出错:" + e.getMessage()); res.put(CmbcConstants.ERROR_NO_KEY, 1); res.put(CmbcConstants.ERROR_INFO_KEY, HTTP_POST_WRONG2); } return res; }
2、组装HttpClient请求并发送。
public static HttpResult post(String requestUrl, String requestName, String requestStr, String requestFileName, File file, String fileName, String encoding, int timeout, CookieStore cookies) throws Exception { return HttpHelper.post(requestUrl, requestName, requestStr, requestFileName, file, fileName, encoding, timeout, cookies, null, null, null ); }
/** * * @author cgw * @date 2016-05-04 * * @param url * @param requestInfoName * @param requestInfo * @param requestFileName * @param file * @param fileName * @param encoding * @param timeOut * @param cookies * @param headers * @param localAddress * @param conType * @return * @throws Exception */ public static HttpResult post(String url, String requestInfoName, String requestInfo, String requestFileName, File file, String fileName, String encoding, int timeOut, CookieStore cookies, List<Header> headers, String localAddress, String conType) throws Exception { DefaultHttpClient httpclient = useTrustingTrustManager( new DefaultHttpClient(), url); httpclient.getParams().setIntParameter("http.socket.timeout", timeOut * 1000); if (null != localAddress && "".equals(localAddress) == false) { InetAddress localBinding = Inet4Address.getByName(localAddress); httpclient.getParams().setParameter(ConnRouteParams.LOCAL_ADDRESS, localBinding); } HttpContext localContext = new BasicHttpContext(); if (cookies != null) { localContext.setAttribute(ClientContext.COOKIE_STORE, cookies); } HttpPost httppost = new HttpPost(url); String contentType = null; if (headers != null) { int size = headers.size(); for (int i = 0; i < size; i++) { Header h = headers.get(i); if (h.getName().startsWith("$x-param") == false) { httppost.addHeader(h); } if ("Content-Type".equalsIgnoreCase(h.getName()) == true) { contentType = h.getValue(); } } } /** ----- file 转 multipartfile start ---- by cgw -- FileItem fileItem = new DiskFileItem( "file", // 表单参数名 ContentType.APPLICATION_OCTET_STREAM.toString(), // 文件类型 false, // 是否为表单格式 fileName, // 文件名 52428800, // 超过50M存在磁盘上 file // 文件 ); // 将F 4000 ile内容写入fileItem,使用org.apache.commons.io.IOUtils IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream()); // 创建multipartfile MultipartFile multipartFile = new CommonsMultipartFile(fileItem); InputStreamBody inputStreamBody2 = new InputStreamBody(multipartFile.getInputStream(), multipartFile.getOriginalFilename()); ----- file 转 multipartfile end ---- by cgw --**/ InputStream in = new FileInputStream(file); InputStreamBody inputStreamBody = new InputStreamBody(in, fileName); MultipartEntity reqEntity = new MultipartEntity(); Charset encode = Charset.forName(encoding); reqEntity.addPart(requestInfoName, new StringBody(requestInfo,encode)); reqEntity.addPart(requestFileName, inputStreamBody); //reqEntity.addPart("FileData", inputStreamBody2); //reqEntity.addPart("FileData", new FileBody(file, "application/zip", encoding)); try { httppost.setEntity(reqEntity); } catch (Exception e) { throw e; } HttpResult httpResult = HttpResult.empty(); HttpResponse response; try { response = httpclient.execute(httppost, localContext); httpResult = new HttpResult(localContext, response); } catch (Exception e) { httppost.abort(); throw e; } finally { if (httpclient != null && httpclient.getConnectionManager() != null) { httpclient.getConnectionManager().shutdown(); } } httpclient.getConnectionManager().shutdown(); return httpResult; }
3、服务器端接收。
这里只写一下接收文件的部分MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile cf = multipartRequest.getFile("FileData"); InputStream in = cf.getInputStream(); FileOutputStream fos = null; try { // 打开一个已存在文件的输出流 fos = new FileOutputStream("E:\\"+filenum+".zip"); filenum++; } catch (FileNotFoundException e) { e.printStackTrace(); } // 将输入流is写入文件输出流fos中 int ch = 0; try { while((ch=in.read()) != -1){ fos.write(ch); } } catch (IOException e1) { e1.printStackTrace(); } finally{ //关闭输入流等(略) fos.close(); in.close(); }
4、记录一下遇到的坑。
1、之前httpclient直接设置了Content-Type为multipart/form-data。导致一个出现一个boundary的错误。
其实这里不需要设置boundary,MultipartEntity(addPart())会根据我们add的内容为我们分别设置好Content-Type。
2、
返回413错误 :Request Entity Too Large
目测是对方apache服务器配置问题导致我这边没有发送完整个请求就收到413.
相关文章推荐
- HTTP 错误 404.15 - Not Found 请求筛选模块被配置为拒绝包含的查询字符串过长的请求。
- 网络协议概述:物理层、连接层、网络层、传输层、应用层详解
- 最小路径覆盖问题[网络流24题之3]
- UNIX网络编程:消息队列
- 卷积神经网络(CNN)在句子建模上的应用
- 基于振动图像纹理特征识别 的滚动轴承故障程度诊断方法研究
- TCP/IP协议与UDP/IP协议的区别
- Android----ListView的使用--->加载网络图片
- 微博营销实战4——网络舆论的监控与应对
- VirtualBox centos 6.5 minimal 开启网络
- 设置fedora23的网络配置
- 封装HttpURLConnection
- 以太网和PPPOE网络下MTU和MSS的关系
- BA无标度网络模型构造算法
- HttpClient调用第三方系统详解
- http://cmsblogs.com/?p=1530
- 用SymPy简化神经网络的求导(微分)
- WS小世界网络模型构造算法
- 深度学习简介(一)——卷积神经网络
- 淑梅派树莓派做wifi热点并安装Facebook网络模拟测试工具