http及httpclient4.4简单介绍

来源:互联网 发布:淘宝买枪的暗语 编辑:程序博客网 时间:2024/04/30 17:25


HTTP报文是面向文本的,报文中的每个字段都是一些ASCII码串,个个字段长度也是不确定的,HTTP有两类报文:请求报文和相应报文,这两类是我们常用且需要关心的;


HTTP请求报文:


一个HTTP请求报文包含四部分:请求行(request line),请求头部(header)、空行和请求数据4个部分组成;


1. HTTP请求


所有的http请求都由:方法名,请求url,HTTP协议组成。HttpClient支持HTTP/1.1支持的所有方法:GET,HEAD,POST,PUT,DELETE,TRACE和OPTIONS,HttpClient中都有一个特定的类与之对应:HttpGet(常用),HttpHeadt(不常用,作为服务连接检测比较好),HttpPostt(常用),HttpPut,HttpDelete,HttpTrace和HttpOptions。


2. HTTP响应

HTTP响应是HTTP请求发送到服务端处理后响应到客户端的消息。响应第一行是协议与协议版本号,接着是数字状态码和一些文本信息,示例演示一下看看执行结果:


3. HTTP消息头(开发需要关心)

HTTP消息头(header)包含多个消息描述的信息,例如:内容长度,内容类型等。HttpClient提供的方法有检索,添加,删除和枚举等操作。
如: BasicHeader

4. HTTP Entity(常用的数据封装对象)

如:UrlEncodedFormEntity(键值对封装),StringEntity(数据封装,如json等);



用了一段时间httpclient,个人感觉httpclient是对http请求和返回进行了一些封装,提供了很多灵活的对象和方法供使用者根据不同业务场景使用,同时也提供了一些工具类,方面开发人员快速开发;


------------------------------------------------------------------------httpclean请求示例-post普通数据请求--------------------------------------------------------------------------------------------------------------

String url = "请求url";
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();nameValuePairs.add(new BasicNameValuePair(key1, value1));
nameValuePairs.add(new BasicNameValuePair(key2, value2));


HttpPost httppost = new HttpPost(url);String rs = "";UrlEncodedFormEntity uefEntity;CloseableHttpResponse response = null;HttpEntity entity = null;httppost.setConfig(getHttpConfig(timeout));httppost.setHeader();try {   if(nameValuePairs!=null){      uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");      httppost.setEntity(uefEntity);   }}  catch (UnsupportedEncodingException e) {   e.printStackTrace();}try {   response = httpclient.execute(httppost);   entity = response.getEntity();   if(entity != null) {      rs = EntityUtils.toString(entity);   }} catch (ClientProtocolException e) {   e.printStackTrace();} catch (IOException e) {   e.printStackTrace();} finally {   if(response != null) {      try {         response.close();      } catch (IOException e) {         e.printStackTrace();      }   }}
System.out.println("response结果:"+rs)







0 0