【Java】Apache HttpClient 4.3开发指南(三个例子)

Apache HttpClient 4.3开发指南(三个例子)

首次接触HttpClient ,参考其他文章中的介绍说 4.3与其他3.x-4.x版本有些大的改变,参考其他大牛的文章

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.List;  
  
import org.apache.http.Consts;  
import org.apache.http.Header;  
import org.apache.http.HttpEntity;  
import org.apache.http.HttpHeaders;  
import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;  
import org.apache.http.client.config.RequestConfig;  
import org.apache.http.client.entity.UrlEncodedFormEntity;  
import org.apache.http.client.methods.HttpGet;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.impl.client.CloseableHttpClient;  
import org.apache.http.impl.client.HttpClientBuilder;  
import org.apache.http.impl.client.HttpClients;  
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils;  
  
//java.net.UnknownHostException  
public class Test {  
  
    /** 
     * 简单的获取一个HTML页面的内容 
     */  
    public static void getHTML() {  
        CloseableHttpClient httpClient = null;  
        try {  
            // httpClient = HttpClients.createDefault(); //生成一个httpclient对象, 同下代码  
            httpClient = HttpClientBuilder.create().build();  
  
            HttpGet httpGet = new HttpGet("http://www.baidu.com/");  
  
            // 配置请求的超时设置  
            RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).build();   
            httpGet.setConfig(config);  
  
            // 配置请求的HEADER部分  
            httpGet.addHeader(HttpHeaders.ACCEPT, "application/xml");  
              
            HttpResponse response = httpClient.execute(httpGet);  
            System.out.println("状态码:" + response.getStatusLine()); // 返回响应状态信息  
              
             // 获取响应消息实体  
            HttpEntity entity = response.getEntity();  
              
            // 获取响应的所有HEADER部分  
            System.out.println(Arrays.toString(response.getAllHeaders()));  
  
             // 判断响应实体是否为空  
            if (entity != null) {  
                System.out.println("contentEncoding(内容编码):" + entity.getContentEncoding());  
                System.out.println("response content(相应内容):" + EntityUtils.toString(entity, "UTF-8"));  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭或释放资源  
            try {  
                httpClient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * 下载一个文件到本地 
     */  
    public static void downloadFile() {  
        CloseableHttpClient httpClient = null;  
        InputStream iStream = null;  
        FileOutputStream foStream = null;  
  
        try {  
            httpClient = HttpClients.createDefault(); // 生成一个httpclient对象  
            HttpGet httpGet = new HttpGet("http://ww2.sinaimg.cn/large/9d57a855jw1dqpv9fp4yuj.jpg"); // 传入一张图片的地址  
  
            System.out.println("文件正在下载...");  
            HttpResponse response = httpClient.execute(httpGet);  
            HttpEntity entity = response.getEntity();  
  
            iStream = entity.getContent();  
            File file = new File("d:/cat.jpg"); // 图片对象  
            foStream = new FileOutputStream(file);  
            int i = -1;  
            byte[] tmp = new byte[1024];  
            while ((i = iStream.read(tmp)) != -1) {  
                foStream.write(tmp, 0, i);  
            }  
            System.out.println("文件下载完毕...");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                foStream.flush();  
                foStream.close();  
                iStream.close();  
                httpClient.close();  
                System.out.println("数据流已关闭....");  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * post模拟人人网登陆,人人网的用户名、密码、Action参数可以通过在线人人网页面源代码查看 
     */  
    public static void loginRR() {  
        String account = "x-rapido@163.com"; // 人人网帐号和密码  
        String passWord = "x-rapido";  
  
        CloseableHttpClient httpClient = null; // 生成一个httpclient对象  
        HttpPost httpPost = null; // 用于提交登录数据  
        HttpGet httpGet = null; // 获得登录后的页面  
        String login_success;// 用于构造上面的HttpGet  
  
        httpClient = HttpClients.createDefault();  
        httpPost = new HttpPost("http://www.renren.com/PLogin.do"); // 人人网登录action  
  
        try {  
            List<NameValuePair> params = new ArrayList<NameValuePair>(); // 封装提交参数  
            params.add(new BasicNameValuePair("email", account));  
            params.add(new BasicNameValuePair("password", passWord));  
            httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8)); // 可对参数进行编码  
  
            HttpResponse response = httpClient.execute(httpPost); // POST请求,  
                                                                    // 提交登录数据  
            System.out.println("response.getAllHeaders(): " + Arrays.toString(response.getAllHeaders()));  
  
            Header locationHeader = response.getFirstHeader("location"); // 获得跳转的页面  
            if (locationHeader == null) {  
                System.out.println("登录不成功,请稍候再试...");  
                return;  
            }  
            login_success = locationHeader.getValue(); // 登录成功后跳转页面  
            System.out.println("登录成功后的挑战网页名称:" + locationHeader.getName() + ", 地址:" + login_success);  
            httpGet = new HttpGet(login_success);  
  
            HttpResponse response2 = httpClient.execute(httpGet);  
            // 输出登录成功后的页面  
            String str = EntityUtils.toString(response2.getEntity());  
            System.out.println(str);  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            httpPost.abort();  
            httpGet.abort();  
            try {  
                httpClient.close();  
                System.out.println("完成登录...");  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
  
    }  
  
    public static void main(String[] args) {  
        getHTML();  
        // downloadFile();  
        // loginRR();  
    }  
  
}

打印内容如下示例:

Apache HttpClient 4.3开发指南(三个例子)

一般并不需要设置很多参数,项目需要即可如下简单配置

/** 
 * 简单的获取一个HTML页面的内容 
 */  
public static void getHTML() {  
    CloseableHttpClient httpClient = null;  
    try {  
        // httpClient = HttpClients.createDefault(); //生成一个httpclient对象,  同下代码  
        httpClient = HttpClientBuilder.create().build();  
  
        HttpGet httpGet = new HttpGet("http://www.baidu.com/");  
        HttpResponse response = httpClient.execute(httpGet);  
          
         // 获取响应消息实体  
        HttpEntity entity = response.getEntity();  
  
         // 判断响应实体是否为空  
        if (entity != null) {  
            System.out.println("response content(相应内容):" + EntityUtils.toString(entity, "UTF-8"));  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        // 关闭或释放资源  
        try {  
            httpClient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

模拟带文件上传的表单提交 http://blog.csdn.net/c_vincente/article/details/17001153

注意:

设置请求的超时验证的2种方式(必须),不然会一直请求下去会造成请求很久无响应  

HttpClient3.X和HttpClient4.X的不同超时设置参考文章:http://blog.csdn.net/xiaokui_wingfly/article/details/42595905

(1)RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).build();  
    httpGet.setConfig(config);  
(2)RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)  
                      .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();  
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

比如下面的联接异常处理

/** 
 * get方式测试服务器联接  
 */  
public static void getServerData() {  
    CloseableHttpClient httpClient = null;  
    try {  
        RequestConfig defaultRequestConfig = RequestConfig.custom()  
                  .setSocketTimeout(5000).setConnectTimeout(5000)  
                  .setConnectionRequestTimeout(5000)  
                  .setStaleConnectionCheckEnabled(true).build();  
        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();  
          
        HttpGet httpGet = new HttpGet("http://172.25.0.119:7015/DCMapService/servlet/ProxyServlet?type=sg_grid&x=507638.3125000&y=303547.9687500");  
        HttpResponse response = httpClient.execute(httpGet);  
        HttpEntity entity = response.getEntity();  
          
        // 判断响应实体是否为空  
        if (entity != null) {  
            if (entity.toString().trim().equals("")) {  
                System.out.println("空");  
            }  
            System.out.println("server get:" + EntityUtils.toString(entity, "gbk"));  
        }  
    }catch (NoRouteToHostException e) {  
        System.out.println("无网络");  
    }catch (ConnectTimeoutException e) {  
        System.out.println("远程服务已断开,请稍候尝试");  
    }catch (SocketTimeoutException e) {  
        System.out.println("请求超时,请稍候尝试");  
    }catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        try {   // 关闭或释放资源  
            httpClient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}


HttpClient API地址:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/package-summary.html


未经允许请勿转载:程序喵 » 【Java】Apache HttpClient 4.3开发指南(三个例子)

点  赞 (0) 打  赏
分享到: