HttpClient使用详解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient使用详解相关的知识,希望对你有一定的参考价值。
HttpClient:是一个接口
首先需要先创建一个DefaultHttpClient的实例
HttpClient httpClient=new DefaultHttpClient();
发送GET请求:
先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可:
HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);
httpClient.execute(httpGet);
发送POST请求:
创建一个HttpPost对象,传入目标的网络地址:
HttpPost httpPost=new HttpPost(“http://www.baidu.com”);
通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入:
List<NameValuePair>params=newArrayList<NameValuePair>();
Params.add(new BasicNameValuePair(“username”,”admin”));
Params.add(new BasicNameValuePair(“password”,”123456”));
UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”);
httpPost.setEntity(entity);
调用HttpClient的execute()方法,并将HttpPost对象传入即可:
HttpClient.execute(HttpPost);
执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所有信息就保护在HttpResponse里面.
先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了:
If(httpResponse.getStatusLine().getStatusCode()==200){
//请求和响应都成功了
HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
Stringresponse=EntityUtils.toString(entity,”utf-8”);//用 EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符 集指定成utf-8就可以了
}
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我 们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮 性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
一、简介
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。 HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和htmlUnit都使用了HttpClient。
下载地址: http://hc.apache.org/downloads.cgi
二、特性
1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1
2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支持HTTPS协议。
4. 通过Http代理建立透明的连接。
5. 利用CONNECT方法通过Http代理建立隧道的https连接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理Set-Cookie中的Cookie。
11. 插件式的自定义Cookie策略。
12. Request的输出流可以避免流中内容直接缓冲到socket服务器。
13. Response的输入流可以有效的从socket服务器直接读取相应内容。
14. 在http1.0和http1.1中利用KeepAlive保持持久连接。
15. 直接获取服务器发送的response code和 headers。
16. 设置连接超时的能力。
17. 实验性的支持http1.1 response caching。
18. 源代码基于Apache License 可免费获取。
三、使用方法
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器 的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
四、实例
- package com.test;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.security.KeyManagementException;
- import java.security.KeyStore;
- import java.security.KeyStoreException;
- import java.security.NoSuchAlgorithmException;
- import java.security.cert.CertificateException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.net.ssl.SSLContext;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.ParseException;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
- import org.apache.http.conn.ssl.SSLContexts;
- import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.entity.mime.content.FileBody;
- import org.apache.http.entity.mime.content.StringBody;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- import org.junit.Test;
- public class HttpClientTest {
- @Test
- public void jUnitTest() {
- get();
- }
- /**
- * HttpClient连接SSL
- */
- public void ssl() {
- CloseableHttpClient httpclient = null;
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
- try {
- // 加载keyStore d:\\tomcat.keystore
- trustStore.load(instream, "123456".toCharArray());
- } catch (CertificateException e) {
- e.printStackTrace();
- } finally {
- try {
- instream.close();
- } catch (Exception ignore) {
- }
- }
- // 相信自己的CA和所有自签名的证书
- SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
- // 只允许使用TLSv1协议
- SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
- SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
- httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
- // 创建http请求(get方式)
- HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
- System.out.println("executing request" + httpget.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- HttpEntity entity = response.getEntity();
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- if (entity != null) {
- System.out.println("Response content length: " + entity.getContentLength());
- System.out.println(EntityUtils.toString(entity));
- EntityUtils.consume(entity);
- }
- } finally {
- response.close();
- }
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (KeyManagementException e) {
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (KeyStoreException e) {
- e.printStackTrace();
- } finally {
- if (httpclient != null) {
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * post方式提交表单(模拟用户登录请求)
- */
- public void postForm() {
- // 创建默认的httpClient实例.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- // 创建httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- // 创建参数队列
- List<namevaluepair> formparams = new ArrayList<namevaluepair>();
- formparams.add(new BasicNameValuePair("username", "admin"));
- formparams.add(new BasicNameValuePair("password", "123456"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
- System.out.println("--------------------------------------");
- }
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
- */
- public void post() {
- // 创建默认的httpClient实例.
- CloseableHttpClient httpclient = HttpClients.createDefault();
- // 创建httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- // 创建参数队列
- List<namevaluepair> formparams = new ArrayList<namevaluepair>();
- formparams.add(new BasicNameValuePair("type", "house"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
- System.out.println("--------------------------------------");
- }
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 发送 get请求
- */
- public void get() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- // 创建httpget.
- HttpGet httpget = new HttpGet("http://www.baidu.com/");
- System.out.println("executing request " + httpget.getURI());
- // 执行get请求.
- CloseableHttpResponse response = httpclient.execute(httpget);
- try {
- // 获取响应实体
- HttpEntity entity = response.getEntity();
- System.out.println("--------------------------------------");
- // 打印响应状态
- System.out.println(response.getStatusLine());
- if (entity != null) {
- // 打印响应内容长度
- System.out.println("Response content length: " + entity.getContentLength());
- // 打印响应内容
- System.out.println("Response content: " + EntityUtils.toString(entity));
- }
- System.out.println("------------------------------------");
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭连接,释放资源
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 上传文件
- */
- public void upload() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
- FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
- StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
- HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
- httppost.setEntity(reqEntity);
- System.out.println("executing request " + httppost.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- HttpEntity resEntity = response.getEntity();
- if (resEntity != null) {
- System.out.println("Response content length: " + resEntity.getContentLength());
- }
- EntityUtils.consume(resEntity);
- } finally {
- response.close();
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- httpclient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
package com.jia.networktest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
public static final int SHOW_HTTPCLIENT = 1;
private Button send_request;
private TextView responseText;
private Button btn_httpClient;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
case SHOW_HTTPCLIENT:
String m_httpClient = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(m_httpClient);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_request = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
btn_httpClient = (Button) findViewById(R.id.HttpClient);
send_request.setOnClickListener(this);
btn_httpClient.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
} else if (v.getId() == R.id.HttpClient) {
sendRequestWithHttpClient();
}
}
private void sendRequestWithHttpClient() {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",
"[email protected]"));
params.add(new BasicNameValuePair("password", "yaowentian"));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
params, "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 请求和响应都成功了
HttpEntity entity = httpResponse.getEntity();// 获取到一个HttpEntity实例
String response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()这个方法将HttpEntity转换成字符串
Message message = new Message();
message.what = SHOW_HTTPCLIENT;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
out.writeBytes("[email protected]&password=yaowentian");
InputStream in = connection.getInputStream();
// 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
// 将服务器返回的结果存放到message中
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
首先要注意的有以下几点:
1、httpclient连接后资源释放问题很重要,就跟我们用database connection要释放资源一样。
2、https网站采用ssl加密传输,证书导入要注意。
3、做这样的项目最好先了解下http协义,比如302,301,200,404返回代码的含义(这是最基本的),cookie,session的机制。
4、httpclient的redirect状态默认是自动的,这在很大程度上给开发者很大的方便(如一些授权获得cookie),但是有时要手动管理下,比如
有时会遇到CircularRedirectException异常,出现这样的情况是因为返回的头文件中location值指向之前重复(端口号可以不同)地址,导致可能会出现死
循环递归重定向,这时可以手动关闭:method.setFollowRedirects(false)
5、有的网站会先判别用户的请求是否是来自浏览器,如不是,则返回不正确的文本,所以用httpclient抓取信息时在头部加入如下信息:
header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows
NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR
2.0.50727)");
6、当post请求提交数据时要改变默认编码,不然的话提交上去的数据会出现乱码。重写postMethod的setContentCharSet()方法就可以了:
下面写一个通用类来处理request请求返回的文本:
- /*
- * HttpRequestProxy.java
- *
- * Created on November 3, 2008, 9:53 AM
- */
- package cn.com.mozat.net;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import org.apache.commons.httpclient.Header;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpException;
- import org.apache.commons.httpclient.HttpMethod;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.commons.httpclient.SimpleHttpConnectionManager;
- import org.apache.commons.httpclient.methods.GetMethod;
- import org.apache.commons.httpclient.methods.PostMethod;
- import cn.com.mozat.exception.CustomException;
- /**
- *
- * @author bird email:[email protected]
- *
- * 2008-11-4 09:49:48
- */
- public class HttpRequestProxy{
- //超时间隔
- private static int connectTimeOut = 60000;
- //让connectionmanager管理httpclientconnection时是否关闭连接
- private static boolean alwaysClose = false;
- //返回数据编码格式
- private String encoding = "UTF-8";
- private final HttpClient client = new HttpClient(new SimpleHttpConnectionManager(alwaysClose));
- public HttpClient getHttpClient(){
- return client;
- }
- /**
- * 用法:
- * HttpRequestProxy hrp = new HttpRequestProxy();
- * hrp.doRequest("http://www.163.com",null,null,"gbk");
- *
- * @param url 请求的资源URL
- * @param postData POST请求时form表单封装的数据 没有时传null
- * @param header request请求时附带的头信息(header) 没有时传null
- * @param encoding response返回的信息编码格式 没有时传null
- * @return response返回的文本数据
- * @throws CustomException
- */
- public String doRequest(String url,Map postData,Map header,String encoding) throws CustomException{
- String responseString = null;
- //头部请求信息
- Header[] headers = null;
- if(header != null){
- Set entrySet = header.entrySet();
- int dataLength = entrySet.size();
- headers= new Header[dataLength];
- int i = 0;
- for(Iterator itor = entrySet.iterator();itor.hasNext();){
- Map.Entry entry = (Map.Entry)itor.next();
- headers[i++] = new Header(entry.getKey().toString(),entry.getValue().toString());
- }
- }
- //post方式
- if(postData!=null){
- PostMethod postRequest = new PostMethod(url.trim());
- if(headers != null){
- for(int i = 0;i < headers.length;i++){
- postRequest.setRequestHeader(headers[i]);
- }
- }
- Set entrySet = postData.entrySet();
- int dataLength = entrySet.size();
- NameValuePair[] params = new NameValuePair[dataLength];
- int i = 0;
- for(Iterator itor = entrySet.iterator();itor.hasNext();){
- Map.Entry entry = (Map.Entry)itor.next();
- params[i++] = new NameValuePair(entry.getKey().toString(),entry.getValue().toString());
- }
- postRequest.setRequestBody(params);
- try {
- responseString = this.executeMethod(postRequest,encoding);
- } catch (CustomException e) {
- throw e;
- } finally{
- postRequest.releaseConnection();
- }
- }
- //get方式
- if(postData == null){
- GetMethod getRequest = new GetMethod(url.trim());
- if(headers != null){
- for(int i = 0;i < headers.length;i++){
- getRequest.setRequestHeader(headers[i]);
- }
- }
- try {
- responseString = this.executeMethod(getRequest,encoding);
- } catch (CustomException e) {
- e.printStackTrace();
- throw e;
- }finally{
- getRequest.releaseConnection();
- }
- }
- return responseString;
- }
- private String executeMethod(HttpMethod request, String encoding) throws CustomException{
- String responseContent = null;
- InputStream responseStream = null;
- BufferedReader rd = null;
- try {
- this.getHttpClient().executeMethod(request);
- if(encoding != null){
- responseStream = request.getResponseBodyAsStream();
- rd = new BufferedReader(new InputStreamReader(responseStream,
- encoding));
- String tempLine = rd.readLine();
- StringBuffer tempStr = new StringBuffer();
- String crlf=System.getProperty("line.separator");
- while (tempLine != null)
- {
- tempStr.append(tempLine);
- tempStr.append(crlf);
- tempLine = rd.readLine();
- }
- responseContent = tempStr.toString();
- }else
- responseContent = request.getResponseBodyAsString();
- Header locationHeader = request.getResponseHeader("location");
- //返回代码为302,301时,表示页面己经重定向,则重新请求location的url,这在
- //一些登录授权取cookie时很重要
- if (locationHeader != null) {
- String redirectUrl = locationHeader.getValue();
- this.doRequest(redirectUrl, null, null,null);
- }
- } catch (HttpException e) {
- throw new CustomException(e.getMessage());
- } catch (IOException e) {
- throw new CustomException(e.getMessage());
- } finally{
- if(rd != null)
- try {
- rd.close();
- } catch (IOException e) {
- throw new CustomException(e.getMessage());
- }
- if(responseStream != null)
- try {
- responseStream.close();
- } catch (IOException e) {
- throw new CustomException(e.getMessage());
- }
- }
- return responseContent;
- }
- /**
- * 特殊请求数据,这样的请求往往会出现redirect本身而出现递归死循环重定向
- * 所以单独写成一个请求方法
- * 比如现在请求的url为:http://localhost:8080/demo/index.jsp
- * 返回代码为302 头部信息中location值为:http://localhost:8083/demo/index.jsp
- * 这时httpclient认为进入递归死循环重定向,抛出CircularRedirectException异常
- * @param url
- * @return
- * @throws CustomException
- */
- public String doSpecialRequest(String url,int count,String encoding) throws CustomException{
- String str = null;
- InputStream responseStream = null;
- BufferedReader rd = null;
- GetMethod getRequest = new GetMethod(url);
- //关闭httpclient自动重定向动能
- getRequest.setFollowRedirects(false);
- try {
- this.client.executeMethod(getRequest);
- Header header = getRequest.getResponseHeader("location");
- if(header!= null){
- //请求重定向后的URL,count同时加1
- this.doSpecialRequest(header.getValue(),count+1, encoding);
- }
- //这里用count作为标志位,当count为0时才返回请求的URL文本,
- //这样就可以忽略所有的递归重定向时返回文本流操作,提高性能