码迷,mamicode.com
首页 > 编程语言 > 详细

java中HttpClient的使用

时间:2017-06-07 20:53:16      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:服务器   ble   添加   tps   params   conf   keyset   ash   关闭   

HttpClient的使用步骤:

1、使用Apache的HttpClient发送GET和POST请求的步骤如下: 

1. 使用帮助类HttpClients创建CloseableHttpClient对象. 2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例. 
3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数. 
4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体. 
5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例 
6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等. 
7. 最后关闭HttpClient资源.

2、使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

1. 创建HttpClient对象,HttpClients.createDefault()。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象,HttpPost httpPost = new HttpPost(url)。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();valuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));httpPost.setEntity(formEntity)。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

httpClient实例:

实例一:

package http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClients;





public class HttpTest {

	public Boolean isRequestSuccessful(HttpResponse httpresponse){
		return httpresponse.getStatusLine().getStatusCode()==200;
	}
	public String HttpPost(String param1,String param2,String url) throws Exception{
		Map<String,String> personMap = new HashMap<String,String>();
		personMap.put("param1",param1);
		personMap.put("param1",param2);
		List<NameValuePair> list = new LinkedList<NameValuePair>();
		for(Entry<String,String> entry:personMap.entrySet()){
			list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
		}
		HttpPost httpPost = new HttpPost(url);
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,"utf-8");
		httpPost.setEntity(formEntity);
		HttpClient httpCient = HttpClients.CreatDefault();
		HttpResponse httpresponse = null;
		try{
		httpresponse = httpClient.execute(httpPost);
		HttpEntity httpEntity = httpresponse.getEntity();
		String response = EntityUtils.toString(httpEntity, "utf-8");
		return response;
		}catch(ClientProtocolException e){
				System.out.println("http请求失败,uri{},exception{}");
			}catch(IOException e){
				System.out.println("http请求失败,uri{},exception{}");
			}
			return null;
	}
	
}

  

 实例二:

package com.kingdee.opensys.common.util.http;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientHelper {

	private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
	private static HttpClientHelper instance = null;
	private static Lock lock = new ReentrantLock();
	private static CloseableHttpClient httpClient;
	
	public HttpClientHelper(){
		instance = this;
	}
	public static HttpClientHelper getHttpClient(){
		if(instance == null){
			lock.lock();
			try{
				instance = new HttpClientHelper();
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				lock.unlock();
			}
		}
		return instance;
	}
	
	public void init(){
		PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
		pool.setMaxTotal(500);
		pool.setDefaultMaxPerRoute(50);
		httpClient = HttpClientBuilder.create().setConnectionManager(pool).build();
	}
	
	public byte[] executeAndReturnByte(HttpRequestBase request) throws Exception{
		HttpEntity entity = null;
		CloseableHttpResponse response = null;
		byte[] base = new byte[0];
		if(request==null){
			return base;
		}
		if(httpClient==null){
			init();
		}
		if(httpClient==null){
			logger.error("http获取异常");
			return base;
		}
		response = httpClient.execute(request);
		entity = response.getEntity();
		if(response.getStatusLine().getStatusCode()==200){
			String encode = (""+response.getFirstHeader("Content-Encoding")).toLowerCase();
			if(encode.indexOf("gzip")>0){
				entity = new GzipDecompressingEntity(entity);
			}
			base = EntityUtils.toByteArray(entity);
		}else{
			logger.error(""+response.getStatusLine().getStatusCode());
		}
		EntityUtils.consumeQuietly(entity);
		response.close();
		httpClient.close();
		return base;
	}
	
	public String execute(HttpRequestBase request) throws Exception{
		byte[] base = executeAndReturnByte(request);
		if(base==null){
			return null;
		}
		String result = new String(base,"UTF-8");
		return result;
	}
}
package com.kingdee.opensys.common.util.http;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import javax.servlet.http.HttpServletRequest;
public class HttpHelper {

	private static String UTF8 = "UTF-8";
	private static RequestConfig requestConfig;
	
	public static String post(Map<String,String> header,Map<String,String> params,String url) throws Exception{
		HttpPost post = null;
		post = new HttpPost(url);
		if(header!=null){
			for(String key:header.keySet()){
				post.addHeader(key, header.get(key));
			}
		}
		if(params!=null){
			List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
			post.setConfig(getRequestConfig());
			for(String key:params.keySet()){
				list.add(new BasicNameValuePair(key,params.get(key)));
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,UTF8);
			post.setEntity(entity);
		}
		return HttpClientHelper.getHttpClient().execute(post);
	}
	public static String post(Map<String,String> header,String jsonObject,String url) throws Exception{
		HttpPost post = null;
		post = new HttpPost(url);
		if(header!=null){
			for(String key:header.keySet()){
				post.addHeader(key, header.get(key));
			}
		}
		if(jsonObject.isEmpty()){
			throw new Exception("jsonObject不能为空!");
		}
		HttpEntity entity = new StringEntity(jsonObject,"UTF-8");
		return HttpClientHelper.getHttpClient().execute(post);
	}
	public static String post(Map<String,String> params,String url) throws Exception{
		HttpPost post = null;
		post = new HttpPost(url);
		List<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
		post.setConfig(getRequestConfig());
		for(String key:params.keySet()){
			list.add(new BasicNameValuePair(key,params.get(key)));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,UTF8);
		post.setEntity(entity);
		return HttpClientHelper.getHttpClient().execute(post);
	}
	
	public static RequestConfig getRequestConfig(){
		if(requestConfig==null){
			requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)
					.setConnectTimeout(20000).setSocketTimeout(20000).build();
		}
		return requestConfig;
	}
	
	public static String getClientIp(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client_IP");
		}
		if(ip==null||ip.length()==0||"unkonwn".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		if(ip.length()<5){
			ip="0.0.0.0";
		}
		return ip;
	}
}

  

java中HttpClient的使用

标签:服务器   ble   添加   tps   params   conf   keyset   ash   关闭   

原文地址:http://www.cnblogs.com/youzhongmin/p/6940400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!