1. 基础
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 HTTPClient,然后根据作者实际工作经验给出了一些常见问题的解决方法。
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。
2. 简单使用
第一步:创建 HttpClient
CloseableHttpClient httpclient = null;
httpclient = HttpClients.createDefault();
第二步:创建 HttpRequest
HttpRequestBase httpRequest = null;
if(mType == 1){// GEThttpRequest = new HttpGet(uri);}else{// POSThttpRequest = new HttpPost(uri);}
第三步:执行 HttpRequest,获取 Response
response = httpclient.execute(httpRequest);
第四步:解析 Response,包括请求的状态以及请求回来的结果
public static String wrapResponse(HttpResponse response){
String result = "";if(response != null){HttpEntity entity = response.getEntity();InputStream is = null;BufferedReader reader = null;try{is = entity.getContent();reader = new BufferedReader(new InputStreamReader(is,"utf-8"));String line = reader.readLine();while(line != null){result = result+line;line = reader.readLine();}}catch(Exception e){e.printStackTrace();}finally{try {if(is != null){is.close();}if(reader != null){reader.close();}} catch (IOException e) {e.printStackTrace();}}}return result;}
第五步:关闭HttpClient 和 Response
try {
3. 使用proxy代理请求Httpsif(response != null){
response.close();
}if(httpclient != null){
httpclient.close();
}} catch (IOException e) {
e.printStackTrace();}
public static void main(String[] args) throws Exception {// 创建可信任的代理服务CredentialsProvider credsProvider = new BasicCredentialsProvider();credsProvider.setCredentials(new AuthScope("代理服务ip", 8080),new UsernamePasswordCredentials("username", "password"));// 通过代理服务定制化一个HttpClient对象CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();try {// HttpHost target = new HttpHost("corporbank-simp.icbc.com.cn",443,"https");HttpHost proxy = new HttpHost("代理服务ip", 8080);RequestConfig config = RequestConfig.custom().setProxy(proxy).build();// 通过URL访问Https请求,不一定都要设置可信任的服务代理,只需直接访问即可String url ="https://corporbank-simp.icbc.com.cn/icbc/normalbank/index.jsp";HttpGet httpget = new HttpGet(url);System.out.println(httpget.getRequestLine());httpget.setConfig(config);System.out.println("Executing request " + httpget.getRequestLine());CloseableHttpResponse response = httpclient.execute(httpget);//CloseableHttpResponse response = httpclient.execute(target,httpget);// 解析Response的值} finally {httpclient.close();}}