HttpClient

 1、HttpClient简介

在一般情况下,如果只是需要向Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。

为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的Javascript代码;也不会对页面内容进行任何解析、处理。

简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。


2、HttpClient的使用

  1.  创建HttpClient对象。
  2. 如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,执行该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
     

3、HttpClient的实例

  • httpGet
package com.qf.client;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * GET请求示例
 * 
 * @author 小明
 *
 */
public class GetDemo {

    public static void main(String[] args) {
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建HttpGet对象
        HttpGet httpGet = new HttpGet(
                "http://localhost:8080/Servlet/do_login.do?username=test&password=123456");
        CloseableHttpResponse response = null;
        try {
            // 3. 执行GET请求
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine());
            // 4. 获取响应实体
            HttpEntity entity = response.getEntity();
            // 5. 处理响应实体
            if (entity != null) {
                System.out.println("长度:" + entity.getContentLength());
                System.out.println("内容:" + EntityUtils.toString(entity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 释放资源
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • httpPost 
package com.qf.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * POST请求测试
 * 
 * @author 小明
 *
 */
public class PostDemo {

    public static void main(String[] args) {
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 创建HttpPost对象
        HttpPost post = new HttpPost(
                "http://localhost:8080/Servlet/do_login.do");
        // 3. 设置POST请求传递参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", "test"));
        params.add(new BasicNameValuePair("password", "12356"));
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 4. 执行请求并处理响应
        try {
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null){
                System.out.println("响应内容:");
                System.out.println(EntityUtils.toString(entity));
            }
            response.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • httpClients工具类 
<dependency>
		<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.78</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.13</version>
</dependency>
package com.sgcc.nrxt.nms.ios.util;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;


public class HttpClientUtil {
	
	private static Logger logger = Logger.getLogger(HttpClientUtil.class);

	
	private static final int connectionRequestTimeout = 5000;// ms毫秒,从池中获取链接超时时间  
	private static final int connectTimeout = 5000;// ms毫秒,建立链接超时时间  
	private static final int socketTimeout = 30000;// ms毫秒,读取超时时间 
	
	
	/**
	 * HttpClient get
	 * @return
	 */
	public static String doGetData(String url) {
		
		logger.info("sms http请求开始");
		
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		HttpGet httpGet = new HttpGet(url);

		CloseableHttpResponse response = null;

		String resData = ""; //响应json数据
		
		try {
			// 配置信息
			RequestConfig requestConfig = RequestConfig.custom()
					// 设置连接超时时间(单位毫秒)
					.setConnectTimeout(connectTimeout)
					// 设置请求超时时间(单位毫秒)
					.setConnectionRequestTimeout(connectionRequestTimeout)
					// socket读写超时时间(单位毫秒)
					.setSocketTimeout(socketTimeout)
					// 设置是否允许重定向(默认为true)
					.setRedirectsEnabled(true).build();
 
		
			httpGet.setConfig(requestConfig);
 
			response = httpClient.execute(httpGet);
 
			HttpEntity responseEntity = response.getEntity();
		
			if (responseEntity != null) {
				resData = EntityUtils.toString(responseEntity);
			}
			
			logger.info("响应状态为:" + response.getStatusLine());
			logger.info("响应内容为:" + resData);
			
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} catch (ParseException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		logger.info("sms http请求结束");
		
		return resData;
	}
	
	/**
	 * HttpClient post
	 * @return
	 */
	public static String doPostData(String url) {
		
		logger.info("sms http请求开始");
		
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		HttpPost httpPost  = new HttpPost (url);

		CloseableHttpResponse response = null;

		String resData = ""; //响应json数据
		//定义接收数据
		JSONObject result = new JSONObject();
		
		try {
			// 配置信息
			RequestConfig requestConfig = RequestConfig.custom()
					// 设置连接超时时间(单位毫秒)
					.setConnectTimeout(connectTimeout)
					// 设置请求超时时间(单位毫秒)
					.setConnectionRequestTimeout(connectionRequestTimeout)
					// socket读写超时时间(单位毫秒)
					.setSocketTimeout(socketTimeout)
					// 设置是否允许重定向(默认为true)
					.setRedirectsEnabled(true).build()
					.setContentEncoding("UTF-8")
					.setContentType("application/json").build();
 
		
			httpPost.setConfig(requestConfig);
 
			response = httpClient.execute(httpPost);
 
			HttpEntity responseEntity = response.getEntity();
		
			if (response.getStatusLine().getStatusCode() == 200) {
				resData = EntityUtils.toString(responseEntity);
				result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));

			}
			
			logger.info("响应状态为:" + response.getStatusLine());
			logger.info("响应内容为:" + resData);
			
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} catch (ParseException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		logger.info("sms http请求结束");
		
		return resData;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值