HttpClient 获取网页内容

package cn.org.nterc.gtzdms.utils;

import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: 2009-5-11
 * Time: 14:57:44
 * 使用httpClient模拟Http访问,得到访问页面的内容
 */
public class HttpClientUtil {
    private static MultiThreadedHttpConnectionManager connectionManager =
            new MultiThreadedHttpConnectionManager();
    private static final Logger log = Logger.getLogger(HttpClientUtil.class);
    //连接超时时间
    private static int connectionTimeOut = 15000;
    private static int socketTimeOut = 15000;
    private static int readTimeOut = 20000;
    private static int maxConnectionPerHost = 5;
    private static int maxTotalConnections = 40;

    // 标志初始化是否完成的flag
    private static boolean initialed = false;

    // 初始化ConnectionManger的方法
    public static void SetPara() {
        connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
        connectionManager.getParams().setSoTimeout(socketTimeOut);
        connectionManager.getParams().setDefaultMaxConnectionsPerHost(
                maxConnectionPerHost);
        connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
//        connectionManager.get
        initialed = true;
    }

    public static String getResponseByGetMethod(String url){
        return getResponseByGetMethod(url,"GB2312");
    }

    /**
     * 根据GET方法得到页面的返回值
     *
     * @param url 目的地址
     * @param charSet   编码格式
     * @return String   内容
     */
    public static String getResponseByGetMethod(String url,String charSet) {
        HttpClient client = new HttpClient(connectionManager);
        if (!initialed) {
            SetPara();
        }
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setSoTimeout(readTimeOut);
//        System.out.println("timeout = " + client.getHttpConnectionManager().getParams().getConnectionTimeout());
        StringBuffer contentBuffer = new StringBuffer();
        try {
            int statusCode = client.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                InputStream in = getMethod.getResponseBodyAsStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in,getMethod.getResponseCharSet()));
                String inputLine = null;
                while((inputLine = reader.readLine()) != null){
                    contentBuffer.append(inputLine);
                    contentBuffer.append("/n");
                }
                in.close();
                return convertStringCode(contentBuffer.toString(),getMethod.getResponseCharSet(),charSet);
            }else{
                log.error("访问页面出错 返回:  "+getMethod.getStatusLine());
            }

        } catch (IOException e) {
//            System.out.println("e.getMessage() = " + e.getMessage());
            log.error("请求该页面出现异常:" + e.getMessage());
        }finally {
            getMethod.releaseConnection();
        }
        return "";
    }

    /**
     * 设置POST提交的参数
     * @param method    POST方法
     * @param parmMap   参数映射
     */
    private static void setRequestBody(PostMethod method,HashMap parmMap){
        Set keySet = parmMap.keySet();
        Iterator it = keySet.iterator();
        List parmList = new ArrayList();
        while(it.hasNext()){
            String key = (String) it.next();
            String value = (String) parmMap.get(key);
            //设置参数
            NameValuePair nameValuePair = new NameValuePair(key,value);
            parmList.add(nameValuePair);
        }
        method.setRequestBody((NameValuePair[]) parmList.toArray(new NameValuePair[parmList.size()]));
    }

    public static String getgetResponseByPostMethod(String url,HashMap parmMap){
        return getResponseByPostMethod(url,"gb2312",parmMap);
    }
    /**
     * 以POST方法得到网页内容
     * @param url       目的地址
     * @param charSet   编码格式
     * @param parmMap   post 提交的参数,key 参数名称,velue 参数名,均为String类型
     * @return String   返回内容
     */
    public static String getResponseByPostMethod(String url,String charSet, HashMap parmMap){
        HttpClient client = new HttpClient(connectionManager);
        if (!initialed) {
            SetPara();
        }
        PostMethod postMethod = new PostMethod(url);
        if(parmMap != null){
            setRequestBody(postMethod,parmMap);
        }
        postMethod.getParams().setSoTimeout(readTimeOut);
        StringBuffer contentBuffer = new StringBuffer();
        try {
            int statusCode = client.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                InputStream in = postMethod.getResponseBodyAsStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in,postMethod.getResponseCharSet()));
                String inputLine = null;
                while((inputLine = reader.readLine()) != null){
                    contentBuffer.append(inputLine);
                    contentBuffer.append("/n");
                }
                in.close();
                return convertStringCode(contentBuffer.toString(),postMethod.getResponseCharSet(),charSet);
            }else{
                log.error("访问页面出错 返回:  "+postMethod.getStatusLine());
            }

        } catch (IOException e) {
            log.error("请求该页面出现异常:" + e.getMessage());
        }finally {
            postMethod.releaseConnection();
        }
        return "";
    }

    /**
     * 转换编码格式
     * @param source        源字符串
     * @param srcEncode     源字符串编码格式
     * @param destEncode    需要转换的编码格式
     * @return String
     */
    private static String convertStringCode(String source, String srcEncode,
   String destEncode) {
  if (source != null && !"".equals(source)) {
   try {
    return new String(source.getBytes(srcEncode), destEncode);
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return "";
   }
  } else {
   return "";
  }
 }

    public static void main(String[] args) {
//        String content = HttpClientUtil.getResponseByGetMethod("http://www.baidu.com/");
       String content = HttpClientUtil.getResponseByGetMethod("http://www.baidu.com/");
        System.out.println("content = " + content);
    }
}

更多HttpClient的相关内容参考

http://blog.csdn.net/cocojiji5/archive/2008/10/10/3048695.aspx

 

http://www.ibm.com/developerworks/cn/opensource/os-httpclient/#N1004B

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Java编写基于HttpClient和Jsoup的爬虫,需要进行以下步骤: 1. 首先,导入HttpClient和Jsoup的依赖包。可以使用maven或gradle进行依赖管理。 2. 创建一个HttpClient实例,用于发送HTTP请求和接收响应。可以使用HttpClients.createDefault()方法创建一个默认配置的实例。 3. 创建一个HttpGet实例,设置请求URL和请求头信息。可以使用new HttpGet(url)方法创建一个HttpGet实例,然后使用setHeader()方法设置请求头信息。 4. 发送HTTP请求,并获取响应结果。可以使用HttpClient.execute()方法发送请求,并使用HttpResponse.getEntity()方法获取响应实体。 5. 解析HTML内容。可以使用Jsoup.parse()方法解析HTML内容,然后使用Jsoup提供的API进行内容提取和处理。 以下是一个使用HttpClient和Jsoup进行网页爬取的示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; public class WebCrawler { public static void main(String[] args) throws IOException { // 创建一个HttpClient实例 HttpClient httpClient = HttpClients.createDefault(); // 创建一个HttpGet实例,设置请求URL和请求头信息 HttpGet httpGet = new HttpGet("https://www.example.com"); httpGet.setHeader("User-Agent", "Mozilla/5.0"); // 发送HTTP请求,并获取响应结果 HttpResponse httpResponse = httpClient.execute(httpGet); String html = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); // 解析HTML内容 Document document = Jsoup.parse(html); String title = document.title(); System.out.println("Title: " + title); } } ``` 在这个示例中,我们使用HttpClient发送了一个GET请求到https://www.example.com,并获取了响应结果。然后使用Jsoup解析HTML内容,并获取了网页的标题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值