您的位置:首页 > 理论基础 > 计算机网络

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: