HttpClient 初了解
转载:http://avery-leo.iteye.com/blog/207984
Jakarta的httpclient3.1是最新版本,项目中需要用程序模拟浏览器的GET和POST动作。在使用过程中遇到不少问题。
1. 带附件的POST提交
??? 最开始都是使用MultipartPostMethod这个类,现在已经废弃这个类了。API说明:Deprecated.?Use MultipartRequestEntity in conjunction with PostMethod instead.?? 使用PostMethod可以实现的功能,就没有必要再弄一个MultipartPostMethod了。下面是一段最简单的示例:
PostMethod post = new PostMethod(); 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. String url = "http://localhost:8080/HttpTest/Test"; 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类型的请求, String url = "http://localhost:8080/HttpTest/Test"; 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(); }
?