akarta的httpclient3.1是最新版本,项目中需要用程序模拟浏览器的GET和POST动作。在使用过程中遇到不少问题。
1. 带附件的POST提交
最开始都是使用MultipartPostMethod这个类,现在已经废弃这个类了。API说明:Deprecated. UseMultipartRequestEntity
in conjunction with PostMethod
instead. 使用PostMethod可以实现的功能,就没有必要再弄一个MultipartPostMethod了。下面是一段最简单的示例:
NameValuePair[] pairs = new NameValuePair[ 2 ];
pairs[ 0 ] = new NameValuePair( " para1 " , " value1 " );
pairs[ 0 ] = new NameValuePair( " para2 " , " value2 " );
post.setRequestBody(pairs);
HttpClient client = new HttpClient();
try {
client.executeMethod(post);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是针对一般的form形式的提交,而且这个form里面不带附件的。如果带附件,那么这种方法就不起作用,附件上传的参数和普通参数无法一同在服务器获取到。org.apache.commons.httpclient.methods.multipart 这个包就是为处理文件上传这种多形式参数的情况的。最主要的类是Part(代表一种post object),它有二个比较重要的子类:FilePart和StringPart,一个是文件的参数,另一个就是普通的文本参数。它的典型使用方法如下:
PostMethod postMethod = new PostMethod(url);
StringPart sp = new StringPart( " TEXT " , " testValue " );
FilePart fp = new FilePart( " file " , " test.txt " , new File( " ./temp/test.txt " ));
MultipartRequestEntity mrp = new MultipartRequestEntity( new Part[] {sp, fp} , postMethod
.getParams());
postMethod.setRequestEntity(mrp);
// 执行postMethod
HttpClient httpClient = new HttpClient();
try {
httpClient.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
在第二行PostMethod postMethod = new PostMethod();后面,有人说需要使用postMehtod.setRequestHeader("Content-type", "multipart/form-data"); Content-type的请求类型进行更改。但是我在使用过程没有加上这一句,查了一下httpCleint的默认Content-type是 application/octet-stream。应该是没有影响的。对于MIME类型的请求,httpclient建议全用 MulitPartRequestEntity进行包装,就是上面的用法。
2. 参数中文的处理问题
httpclient的默认编码都是ISO-8859-1,那肯定就无法支持中文参数了。引用一下这篇文章:http://thinkbase.net/w/main/Wiki?HttpClient+POST+%E7%9A%84+UTF-8+%E7%BC%96%E7%A0%81%E9%97%AE%E9%A2%98 ,按照作者的说法,就可以正常解决中文编码的问题。其中最关键的是修改EncodingUtil这个类的一个方法实现。另外,FilePart和 StringPart的构造方法都有一个带编码指定的参数,为了减少问题的出现,建议所有的都带上统一的编码,包括 postMethod.getParams()。示例如下:
PostMethod postMethod = new PostMethod(url);
StringPart sp = new StringPart( " TEXT " , " testValue " , " GB2312 " );
FilePart fp = new FilePart( " file " , " test.txt " , new File( " ./temp/test.txt " ), null , " GB2312 " );
postMethod.getParams().setContentCharset( " GB2312 " );
MultipartRequestEntity mrp = new MultipartRequestEntity( new Part[] {sp, fp} , postMethod
.getParams());
postMethod.setRequestEntity(mrp);
// 执行postMethod
HttpClient httpClient = new HttpClient();
try {
httpClient.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient笔记(二)
不多说了,直接上示例:
A服务器:
msURL为:http://192.168.7.203:8080
- /**
- * 发送文件到另一台服务器B
- *
- * @param File file 附件
- * @param serviceType服务类型
- * @param spId id
- * @return
- */
- public String sendApply(File file, String serviceType, String spId) {
- String fromAgentResult = "" ;
- HttpClient client = new HttpClient();
- PostMethod filePost = new PostMethod(msUrl+ "?serviceType=" +serviceType+"&spId=" +spId+ "&type=menu" );
- // MultipartPostMethod filePost = new MultipartPostMethod(msUrl);
- // 若上传的文件比较大 , 可在此设置最大的连接超时时间
- client.getHttpConnectionManager(). getParams().setConnectionTimeout(8000);
- try {
- FilePart fp = new FilePart(file.getName(), file);
- MultipartRequestEntity mrp= new MultipartRequestEntity( new Part[]{fp}, filePost.getParams());
- filePost.setRequestEntity(mrp);
- //使用系统提供的默认的恢复策略
- filePost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler());
- int httpStat = client.executeMethod(filePost);
- System.out.println("httpStat----" +httpStat);
- if (!(httpStat == HttpStatus.SC_OK)) {
- fromAgentResult = "connected fail:" + httpStat;
- } else if (httpStat == HttpStatus.SC_OK) {
- try {
- DocumentBuilderFactory factory = DocumentBuilderFactory
- .newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder
- .parse(filePost.getResponseBodyAsStream());
- doc.normalize();
- // NodeList optypeNL= doc.getElementsByTagName("optype");
- NodeList resultNL = doc.getElementsByTagName("result" );
- // fromAgentOptype=
- // optypeNL.item(0).getFirstChild().getNodeValue();
- fromAgentResult = resultNL.item(0 ).getFirstChild()
- .getNodeValue();
- System.out.println("发送请求完毕,接收状态:" +fromAgentResult);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } catch (HttpException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- filePost.releaseConnection();
- return fromAgentResult;
- }
B服务器接收:
- boolean bl = false ;
- System.out.println("接收文件开始--------------" );
- String serviceType = request.getParameter("serviceType" );
- String spId = request.getParameter("spId" );
- String type = request.getParameter("type" );
- if (type.equals( "menu" )) {
- DiskFileUpload fu = new DiskFileUpload();
- fu.setSizeMax(1000000 );
- List fileItems;
- try {
- fileItems = fu.parseRequest(request);
- Iterator itr = fileItems.iterator();
- while (itr.hasNext()) {
- FileItem fi = (FileItem) itr.next();
- if (!fi.isFormField()) {
- System.out.println("/nNAME: " + fi.getName());
- System.out.println("SIZE: " + fi.getSize());
- try {
- String newFileName = msu.updateName(Integer
- .parseInt(serviceType), spId);
- System.out.println("newFileName---------------"
- + newFileName);
- File fNew = new File(applyFilePath, newFileName);
- fi.write(fNew);
- bl = msu.acceptApply(Integer.parseInt(serviceType),
- spId, newFileName);
- System.out.println(fNew.getAbsolutePath());
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- } else {
- System.out.println("Field =" + fi.getFieldName());
- }
- }
- } catch (FileUploadException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- //下面是返回执行结果
- msu.responseToAS(response, bl);
- System.out.println("接收申请处理完毕,状态:" + bl);
- return null ;
- //msu.responseToAS
- public void responseToAS(HttpServletResponse response, boolean synSuccess) {
- try {
- PrintWriter out = response.getWriter();
- if (synSuccess)
- out
- .println("<?xml version=/"1.0/" encoding=/"UTF-8/"?><root><result>ok</result></root>" );
- else
- out
- .println("<?xml version=/"1.0/" encoding=/"UTF-8/"?><root><result>fail</result></root>" );
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("responseToAS--error" );
- }
- }