java中HttpClient的使用

Posted 没昵称可用

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中HttpClient的使用相关的知识,希望对你有一定的参考价值。

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的使用的主要内容,如果未能解决你的问题,请参考以下文章

在 Java 11 及更高版本中使用 HttpClient 时如何跟踪 HTTP 303 状态代码?

找不到 SSL 证书的 Java HttpClient 错误,在代码中使用证书作为字符串?

WP8,怎么使用HttpClient?

HttpClient“任务被取消”

JAVA通过HttpClient发送HTTP请求的方法

在 URL 查询参数中使用某些字符时出现 Java 9 HttpClient 异常