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;
	}
}

  

时间: 2024-12-29 22:28:24

java中HttpClient的使用的相关文章

Java中httpClient中三种超时设置

本文章给大家介绍一下关于Java中httpClient中的三种超时设置小结 在Apache的HttpClient包中,有三个设置超时的地方: /* 从连接池中取连接的超时时间*/ ConnManagerParams.setTimeout(params, 1000); /*连接超时*/ HttpConnectionParams.setConnectionTimeout(params, 2000); /*请求超时*/ HttpConnectionParams.setSoTimeout(params,

java中httpclient实现digest验证的请求

1.首先介绍如何使用HttpClient发起GET和POST请求   GET 方式: //先将参数放入List,再对参数进行URL编码 List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("param1", "中国")); params.add(new BasicNameValuePa

HTTP协议报文、工作原理及Java中的HTTP通信技术详解

一.web及网络基础       1.HTTP的历史            1.1.HTTP的概念:                 HTTP(Hyper Text Transfer Protocol,超文本传输协议)是一种通信协议,它允许将超文本标记语言(HTML)文档从Web服务器传送到客户端的浏览器.                 它是一个应用层协议,承载于TCP之上.由请求和响应构成,是一个标准的客户端服务器模型            1.2.HTTP的发展历史:          

spring MVC 管理HttpClient---实现在java中直接向Controller发送请求

在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实现. 首先用到的包是httpclient-4.3.5.jar和httpcore-4.3.2.jar 先看下面代码: package module.system.common; import java.io.IOException; import java.util.ArrayList; import

对于url传参的心得。在java中获取数据。。

由于项目抓的紧,发现一个url传参的问题,忙里偷闲整理了一下. 首先得说明,我是要用过另一个项目的url获取json串解析出来给自己的接口使用,这是在java中完成.一般的情况是这样的: 1 public static void main(String args[]){ 2 String url="http://123.56.6.112:2080/ec_app_api/article/getfirst?params={v:1}"; //通过?在后面传参 3 StringBuilder

java中使HttpDelete可以发送body信息

java中使HttpDelete可以发送body信息RESTful api中用到了DELETE方法,android开发的同事遇到了问题,使用HttpDelete执行DELETE操作的时候,不能携带body信息,研究了很久之后找到了解决方法. 我们查看httpclient-4.2.3的源码可以发现,methods包下面包含HttpGet, HttpPost, HttpPut, HttpDelete等类来实现http的常用操作. 其中,HttpPost继承自HttpEntityEnclosingRe

Java 中的纤程库 – Quasar

来源:鸟窝, colobu.com/2016/07/14/Java-Fiber-Quasar/ 如有好文章投稿,请点击 → 这里了解详情 最近遇到的一个问题大概是微服务架构中经常会遇到的一个问题: 服务 A 是我们开发的系统,它的业务需要调用 B.C.D 等多个服务,这些服务是通过http的访问提供的. 问题是 B.C.D 这些服务都是第三方提供的,不能保证它们的响应时间,快的话十几毫秒,慢的话甚至1秒多,所以这些服务的Latency比较长.幸运地是这些服务都是集群部署的,容错率和并发支持都比较

java中的原子操作类AtomicInteger及其实现原理

/** * 一,AtomicInteger 是如何实现原子操作的呢? * * 我们先来看一下getAndIncrement的源代码: * public final int getAndIncrement() { * for (;;) { * int current = get(); // 取得AtomicInteger里存储的数值 * int next = current + 1; // 加1 * if (compareAndSet(current, next)) // 调用compareAnd

记录java中常用的英文单词01

专业缩写 POJO(plain ordinary java object)--简单的java对象 Spring-jdbc--为了使JDBC更加易于使用,spring在JDBC API上定义了一个抽象层,以此建立一个JDBC存取框架 quartz(job scheduling) --批处理框架,定时任务 单词 tokenizer --标记器 strict   [str?kt]  --精准的,绝对的 delimiter  [d?'l?m?t?]--定界符:分隔符 aggregator  [??gr?