Apache HttpClient4.2入门

2023-05-16

 

介绍

 HttpClient Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP协议的客户端编程工具包,并且它支持 HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如 Apache Jakarta上很著名的另外两个开源项目 Cactus HTMLUnit都使用了 HttpClient。本文使用的HttpClient版本为4.2。


HttpClient 特性

  • 基于标准,纯净的java语言.实现了Http1.0和Http1.1
  • 以可扩展的面向对象的结构实现了Http全部的方法 (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE).
  • 支持HTTPS协议.
  • 通过Http代理建立透明的连接.
  • 利用CONNECT 方法通过Http代理建立隧道的https连接.
  • Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos 认证方案.
  • 插件式的自定义认证方案.
  • 便携可靠的套接字工厂使它更容易的使用第三方解决方案.
  • 连接管理器支持多线程应用.支持设置最大连接数,同时支持设置每个主机的最大连接数.发现并关闭过期的连接.
  • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
  • 插件式的自定义Cookie策略.
  • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
  • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
  • 在http1.0和http1.1中利用KeepAlive保持持久连接.
  • 直接获取服务器发送的response code和 headers.
  • 设置连接超时的能力.
  • 实验性的支持http1.1 response caching.

代码示例

获取HttpClient示例:

public HttpClient getClient() {
		HttpClient client = new DefaultHttpClient();// 获取HttpClient对象
		return client;
	}
HttpClient有多个实现,其中DefaultHttpClient为最常用的。

下面将展示如何使用get和post提交请求,还有如何处理查看response数据


使用get方法请求:

public void doGet(String uri) {// get方法提交
		HttpGet getMethod = null;
		getMethod = new HttpGet(uri);// 获取HttpGet对象,使用该对象提交get请求
	    exctueRequest(getMethod);//执行请求,获取HttpResponse对象

	}

使用post方法请求

public void doPost(String uri,HttpEntity entity) {// post方法提交
		HttpPost postMethod = null;

			postMethod = new HttpPost(uri);
			
			postMethod.setEntity(entity);//设置请求实体,例如表单数据
		    exctueRequest(postMethod); // 执行请求,获取HttpResponse对象
	}


exctueRequest()方法详细说明

private HttpResponse exctueRequest(HttpRequestBase request){
	  HttpResponse response=null;
	  
	  try {
		  log.debug("excute request:"+request.getURI());//获取请求uri
		   log.debug("-----------------------------------");
		response=this.getClient().execute(request);//执行请求,获取HttpResponse对象
		showResponse(response);//打印Response信息
		int statuscode = response.getStatusLine().getStatusCode();//根据相应码处理URI重定向
		if((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)){
			
			Header redirectLocation=response.getFirstHeader("Location");//从响应头中获取重定向的uri
			String newuri=redirectLocation.getValue();
		      if((newuri!=null)||(!newuri.equals(""))){
		         log.debug("redirect to "+newuri);
		      request.setURI(new URI(newuri));//重新设置uri
		      response=this.getClient().execute(request);
		      showResponse(response);//打印response信息
		   }else {
			   log.debug("Invalid redirect");
	  }
	  
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally{
		releaseConnection(request);//释放连接,无论成功与否都需要释放连接
	}
	  return response;
	  
  }


打印响应信息

private void showResponse(HttpResponse response) throws ParseException,
			IOException {
		log.debug("requset result:");
		log.debug(response.getStatusLine().toString());// 响应状态
		log.debug("-----------------------------------");

		Header[] heard = response.getAllHeaders();// 响应头
		log.debug("response heard:");
		for (int i = 0; i < heard.length; i++) {
			log.debug(heard[i]);
		}
		log.debug("-----------------------------------");
		HttpEntity entity = response.getEntity();// 响应实体/内容
		log.debug("response content length:" + entity.getContentLength());
		log.debug("response content:");
		log.debug(EntityUtils.toString(entity));
		
	}

释放连接

private void releaseConnection(HttpRequestBase request) {
		if (request != null) {
			request.releaseConnection();
		}
	}


完整代码

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
	private Log log = LogFactory.getLog(this.getClass());

	public HttpClient getClient() {
		HttpClient client = new DefaultHttpClient();// 获取HttpClient对象
		return client;
	}

	private void releaseConnection(HttpRequestBase request) {
		if (request != null) {
			request.releaseConnection();
		}
	}

	private void showResponse(HttpResponse response) throws ParseException,
			IOException {
		log.debug("requset result:");
		log.debug(response.getStatusLine().toString());// 响应状态
		log.debug("-----------------------------------");

		Header[] heard = response.getAllHeaders();// 响应头
		log.debug("response heard:");
		for (int i = 0; i < heard.length; i++) {
			log.debug(heard[i]);
		}
		log.debug("-----------------------------------");
		HttpEntity entity = response.getEntity();// 响应实体/内容
		log.debug("response content length:" + entity.getContentLength());
		log.debug("response content:");
	
		log.debug(EntityUtils.toString(entity));
		
	}

	public void doGet(String uri) {// get方法提交
		HttpGet getMethod = null;
		getMethod = new HttpGet(uri);// 获取HttpGet对象,使用该对象提交get请求
	    exctueRequest(getMethod);
	}

	public void doPost(String uri,HttpEntity entity) {// post方法提交
		        HttpPost postMethod = null;
			postMethod = new HttpPost(uri);
			postMethod.setEntity(entity);//设置请求实体,例如表单数据
		    exctueRequest(postMethod); // 执行请求,获取HttpResponse对象
		

	}

	private HttpResponse exctueRequest(HttpRequestBase request){
	  HttpResponse response=null;
	  
	  try {
		  log.debug("excute request:"+request.getURI());
		   log.debug("-----------------------------------");
		response=this.getClient().execute(request);//执行请求,获取HttpResponse对象
		showResponse(response);
		int statuscode = response.getStatusLine().getStatusCode();//处理重定向
		if((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)){
			
			Header redirectLocation=response.getFirstHeader("Location");
			String newuri=redirectLocation.getValue();
		      if((newuri!=null)||(!newuri.equals(""))){
		         log.debug("redirect to "+newuri);
		      request.setURI(new URI(newuri));
		      response=this.getClient().execute(request);
		      showResponse(response);
		   }else {
			   log.debug("Invalid redirect");
	  }
	  
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally{
		releaseConnection(request);//释放连接
	}
	  return response;
	  
  }

	public static void main(String[] args) {
		HttpClientUtil client = new HttpClientUtil();
		client.doGet("http://www.baidu.com/s?wd=HttpClient");
		
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();// 设置表格参数
		formparams.add(new BasicNameValuePair("usrname", "admin"));
		formparams.add(new BasicNameValuePair("password", "123456"));
		UrlEncodedFormEntity uefEntity = null;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");//获取实体对象
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		client.doPost("http://localhost:8080/U2_project/login.do",uefEntity);
	}
}



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Apache HttpClient4.2入门 的相关文章

随机推荐

  • DIN: 阿里点击率预估之深度兴趣网络

    广告推荐算法系列文章 xff1a 莫比乌斯 百度的下一代query ad匹配算法百度凤巢分布式层次GPU参数服务器架构DIN 阿里点击率预估之深度兴趣网络DIEN 阿里点击率预估之深度兴趣进化网络 本文的知识点来源于参考文献 1 xff0c
  • DIEN: 阿里点击率预估之深度兴趣进化网络

    广告推荐算法系列文章 xff1a 莫比乌斯 百度的下一代query ad匹配算法百度凤巢分布式层次GPU参数服务器架构DIN 阿里点击率预估之深度兴趣网络基于Delaunay图的快速最大内积搜索算法DIEN 阿里点击率预估之深度兴趣进化网络
  • 概率矩阵分解模型 PMF

    本文是论文 一种结合推荐对象间关联关系的社会化推荐算法 的笔记 xff08 上 xff09 因为对其中的概率矩阵分解 Probabilistic Matrix Factorization PMF 不够了解 xff0c 因而我先去脑补了PMF
  • 卷积神经网络

    卷积神经网络 转载请注明 xff1a http blog csdn net stdcoutzyx article details 41596663 自今年七月份以来 xff0c 一直在实验室负责卷积神经网络 xff08 Convolutio
  • DeepID人脸识别算法之三代

    DeepID人脸识别算法之三代 转载请注明 xff1a http blog csdn net stdcoutzyx article details 42091205 DeepID xff0c 目前最强人脸识别算法 xff0c 已经三代 如今
  • 理解dropout

    理解dropout 开篇明义 xff0c dropout是指在深度学习网络的训练过程中 xff0c 对于神经网络单元 xff0c 按照一定的概率将其暂时从网络中丢弃 注意是暂时 xff0c 对于随机梯度下降来说 xff0c 由于是随机丢弃
  • MYSQL— perror 错误码详情

    root 64 localhost cat test nothread py import paramiko import threading import os def ssh2 ip username passwd cmd file p
  • 深度卷积对抗生成网络(DCGAN)

    本文是参考文献 1 的论文笔记 卷积神经网络在有监督学习中的各项任务上都有很好的表现 xff0c 但在无监督学习领域 xff0c 却比较少 本文介绍的算法将有监督学习中的CNN和无监督学习中的GAN结合到了一起 在非CNN条件下 xff0c
  • 看图说话——CNN和LSTM的联合应用

    看图说话是深度学习波及的领域之一 其基本思想是利用卷积神经网络来做图像的特征提取 xff0c 利用LSTM来生成描述 但这算是深度学习中热门的两大模型为数不多的联合应用了 本文是参考文献 1 的笔记 xff0c 论文是比较早的论文 xff0
  • 机器学习经典书籍小结

    机器学习经典书籍小结 转载本博客请注明链接 xff1a http blog csdn net xinzhangyanxiang article details 9069045 博客第一篇文章 1 是转载的 xff0c 也算是开始写博客不经意
  • (一)Tensorflow图像数据转化TFRecord数据格式

    1 TFRecord数据格式 Tensorflow提供的TFRecord文件数据是通过tf train Example Protocol Buffer的格式存储的 数据格式 message Example Features features
  • 【26】Gson原理

    xff08 1 xff09 一个人只要自己不放弃自己 xff0c 整个世界也不会放弃你 xff08 2 xff09 天生我才必有大用 xff08 3 xff09 不能忍受学习之苦就一定要忍受生活之苦 xff0c 这是多么痛苦而深刻的领悟 x
  • Failed to load plugin html: Cannot find module 'eslint-plugin-html'

    npm install save dev eslint plugin html
  • 在 Windows 中启用自动登录功能

    在 Windows 中启用自动登录功能 本文介绍了如何通过将密码和其他相关信息存储在注册表数据库中以配置 Windows 自动执行登录过程 通过使用此功能 xff0c 其他用户可以启动您的计算机并使用您建立的帐户自动登录 为了方便起见 xf
  • Statement与PreparedStatement的区别理解记录

    一 PreparedStatement性能高于Statement xff08 PreparedStatement xff09 属于预编译 xff08 缓存 xff09 xff0c 那怎么预编译的呢 xff0c 源码对比 Statement创
  • Apache CXF文件目录结构及需要jar包

    原文地址 xff1a http blog 163 com a13151055695 64 126 blog static 112087074201143014443273 文件目录结构及相关文件的详细说明 xff1a bin xff08 目
  • 浅析SAX,DOM,JAXP,JDOM与DOM4J之间的关系

    众所周知 xff0c SAX与DOM是JAVA中两大核心XML解析API类库 xff0c 而JAXP JDOM与DOM4J都是基于这两大核心API而衍生出来的 今日兴起看了看相关资料 xff0c 在这里总结总结 SAX与DOM 首先需要说明
  • ctags常用命令(个人整理)

    http blog csdn net myth liu article details 5672572 http chaojimake com 724 html 熟练的使用ctags仅需记住下面几条命 1 ctags languages 6
  • StAX-基于流的拉式XML解析

    最近在学习webservice时 xff0c 发现很多框架 xff0c 技术都在使用StAX作为底层XML解析工具 xff0c 于是今天看了看资料 xff0c 简单学习了下 xff0c 在这里做个总结 简介 StAX xff0c 全称 St
  • Apache HttpClient4.2入门

    介绍 HttpClient 是 Apache Jakarta Common 下的子项目 xff0c 用来提供高效的 最新的 功能丰富的支持 HTTP 协议的客户端编程工具包 xff0c 并且它支持 HTTP 协议最新的版本和建议 HttpC