一般步骤:
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4. 读 response
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理
代码如下:
HttpClient httpClient = new HttpClient(); //构造HttpClient的实例
GetMethod getMethod = new GetMethod("http://www.ibm.com/"); //创建GET方法的实
try {
int statusCode = httpClient.executeMethod(getMethod); //执行getMethod
String response = getMethod.getResponseBodyAsString(); //读取服务器返回的页面代码,这里用的是
字符读法
}catch (HttpException e) {
System.out.println("Please check your provided http address!"); //发生致命的异常,可能是协议不对或者返回
的内容有问题
e.printStackTrace();
} catch (IOException e) { //发生网络异常
e.printStackTrace();
} finally { //释放连接
getMethod.releaseConnection();
}
二,模拟POST方法提交表单。
1)一般POST表单,最简单的示例
PostMethod post = new PostMethod();NameValuePair[] pairs = new NameValuePair[2]; //设置FORM表单里各项内容
pairs[0] = new NameValuePair("para1", "value1");
pairs[1] = new NameValuePair("para2", "value2");
post.setRequestBody(pairs); //将设置好的表单提交上去HttpClient client = new HttpClient(); try {
client.executeMethod(post); //执行,模拟POST方法提交到服务器 }
catch (HttpException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally{ post.releaseConnection();
}
2)带附件的POST表单提交, 最主要的类是Part(代表一种post object),它有二个比较重要的子类:FilePart和StringPart,一个 是文件的参数,另一个就是普通的文本参数。它的典型使用方法如下:
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);
HttpClient httpClient = new HttpClient();
try { httpClient.executeMethod(postMethod); }
catch (HttpException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally{ postMethod.releaseConnection(); }