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();
}
Jakarta的httpclient3.1是最新版本,基本使用方法如下:
一,模拟get方法:
一般步骤:
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4. 读 response
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理
代码如下:
二,模拟POST方法提交表单。
1)一般POST表单,最简单的示例
String url = "*******"; //提交的地址
PostMethod post = new PostMethod(url);
NameValuePair[] pairs = new NameValuePair[ 2 ]; //设置FORM表单里各项内容
NameValuePair p1 = new NameValuePair("login", username);
NameValuePair p2 = new NameValuePair("passwd", password);
NameValuePair[] pairs = { p1, p2 };
post.setRequestBody(pairs); //将设置好的表单提交上去
HttpClient client = new HttpClient();
try {
int status = client.executeMethod(post); //执行,模拟POST方法提交到服务器
if (status == HttpStatus.SC_MOVED_PERMANENTLY || // 处理转向
status == HttpStatus.SC_MOVED_TEMPORARILY) { // 从头中取出转向地址
Header locationHeader = post.getResponseHeader("location");
if (locationHeader != null) {
String location = locationHeader.getValue();
logger.info("頁面跳轉地址是:" + location);
} else {
logger.info("跳轉值為空。");
}
}
} 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();
}