comons_httpClient教程
- 格式:doc
- 大小:119.50 KB
- 文档页数:12
HttpClient教程1、HttpClient相关的资料API:/httpcomponents-client-4.3.x/httpclient/apidocs/index.htmltutorial: /httpcomponents-client-4.3.x/tutorial/html/index.html 【PDF版本】/httpcomponents-client-4.3.x/tutorial/pdf/httpclient-tutorial.pdf2、HttpClient有2个版本org.apache.http.impl.client.HttpClients与mons.httpclient.HttpClient目前后者已被废弃,apache已不再支持。
一般而言,使用HttpClient均需导入httpclient.jar与httpclient-core.jar2个包。
3、使用HttpClient进行网络处理的基本步骤(1)通过get的方式获取到Response对象。
[java] view plaincopy在CODE上查看代码片派生到我的代码片CloseableHttpClienthttpClient = HttpClients.createDefault();HttpGethttpGet = new HttpGet("/");CloseableHttpResponse response = httpClient.execute(httpGet);注意,必需要加上http://的前缀,否则会报:Target host is null异常。
(2)获取Response对象的Entity。
[java] view plaincopy在CODE上查看代码片派生到我的代码片HttpEntity entity = response.getEntity();注:HttpClient将Response的正文及Request的POST/PUT方法中的正文均封装成一个HttpEntity对象。
目录1.1跟我学Commons-HTTPClient3组件技术及应用实例(第1部分) (2)1.1.1Commons-HTTPClient组件的主要功能 (2)1.1.2下载Commons-HTTPClient组件及有关的系统库文件 (3)1.1.3Commons-HTTPClient组件的编程应用 (7)1.1.4应用HttpClient实现登陆系统的应用实例 (13)1.1跟我学Commons-HTTPClient3组件技术及应用实例(第1部分)1.1.1Commons-HTTPClient组件的主要功能1、需要在应用程序中直接访问Web服务器中的目标资源在访问Web服务器中的目标资源时,一般是采用标准的浏览器程序实现。
但现在越来越多的Java 应用程序需要直接通过 HTTP 协议来访问Web服务器中的目标资源——比如RIA中的应用程序客户端程序。
2、常规的方式是应用JDK中的 包中URL和URLConnection类虽然在 JDK 的 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 系统库中所提供的功能不够丰富和也不灵活。
3、HttpClient 是 Apache Jakarta Commons中的一个子项目它为开发人员提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,Commons-HttpClient项目就是专门设计并用来简化HTTP客户端与服务器进行各种通讯编程实现的——它能实现常规的HTTP客户端程序(也就是浏览器程序)的各种功能。
HttpClient组件为开发Web浏览器、Web Service客户端提供了很大的便利。
4、HttpClient组件所提供的主要功能1)实现了http1.0和1.1版中的全部方法(GET、POST、PUT、DELETE、HEAD、OPTIONS和TRACE)和支持Cookie2)支持HTTPS的加密操作,并透明地穿过HTTP代理建立连接3)支持利用Basic、Digest和NTLM加密的认证、支持用于上传大文件的Multi-Part表单POST方法4)不仅能够直接将请求信息流送到服务器的端口,也能够直接读取从服务器的端口送出的应答信息,直接访问由服务器送出的应答代码和头部信息5)支持HTTP/1.0中用KeepAlive和HTTP/1.1中用persistance设置的持久连接6)可设置连接超时时间,并且其中的HttpMethods允许并行请求或高效连接复用1.1.2下载Commons-HTTPClient组件及有关的系统库文件1、Commons-HTTPClient组件中的主要系统库文件commons-httpclient-3.1.jar可以在Apache的官方网站中下载系统库或者httpclient-4.0.3.jar2、还需要commons-codec-1.3.jar文件HttpClient 用到了Apache Jakarta common 下的子项目codec,可以从下图所示的地址下载到最新的common codec,从下载后的压缩包中取出commons-codec-1.x.jar 加到项目的classpath中。
HttpClient的用法HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过HTTP 协议来访问网络资源。
Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。
通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给 httpclient替你完成。
首先,我们必须安装好 HttpClient。
HttpClient 可以在/commons/httpclient/downloads.html下载.HttpClient 用到了 Apache Jakarta common 下的子项目 logging,你可以从这个地址/site/downloads /downloads_commons-logging.cgi下载到 common logging,从下载后的压缩包中取出 commons-logging.jar 加到 CLASSPATH 中.HttpClient 用到了 Apache Jakarta common 下的子项目 codec,你可以从这个地址/site/downloads /downloads_commons-codec.cgi 下载到最新的 common codec,从下载后的压缩包中取出 commons-codec-1.x.jar 加到 CLASSPATH 中1.读取网页(HTTP/HTTPS)内容下面是我们给出的一个简单的例子用来访问某个页面package http.demo;import java.io.IOException;import mons.httpclient.*;import mons.httpclient.methods.*;/*** 最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面* @author Liudong*/public class SimpleClient {public static void main(String[] args) throws IOException{HttpClient client = new HttpClient();//设置代理服务器地址和端口//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);//使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https HttpMethod method = new GetMethod("");//使用POST方法//HttpMethod method = new PostMethod("");client.executeMethod(method);//打印服务器返回的状态System.out.println(method.getStatusLine());//打印返回的信息System.out.println(method.getResponseBodyAsString());//释放连接method.releaseConnection();}}在这个例子中首先创建一个HTTP客户端(HttpClient)的实例,然后选择提交的方法是GET或者 POST,最后在HttpClient实例上执行提交的方法,最后从所选择的提交方法中读取服务器反馈回来的结果。
HttpClient的基本使用HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP 协议的客户端编程工具包,并且它支持HTTP 协议最新的版本和建议。
HttpClient简介HTTP 协议可能是现在Internet 上使用得最多、最重要的协议了,越来越多的Java 应用程序需要直接通过HTTP 协议来访问网络资源。
虽然在JDK 的 包中已经提供了访问HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
所以HttpClient 很好的弥补了JDK 在这一个方面的缺憾。
需要jar包的地址:commons-httpclient-3.1-rc1.jar:/commons/httpclient/downloads.htmlcommons-logging-1.1.jar:/site/downloads/downloads_commons-logging.cgicommons-codec-1.3.jar:/site/downloads/downloads_commons-codec既然是访问服务器,其实主要就是get与post的过程。
在访问网页的时候我们知道,一般的访问就是直接地点击链接得到网页或是通过提交一些数据才能访问到所需的网页。
简单的说,那么前者就是一个get的过程,后者就是post的过程。
一般一个get的过程需要以下几步:1. 创建HttpClient 的实例2. 创建某种连接方法的实例,在这里是GetMethod。
在GetMethod 的构造函数中传入待连接的地址3. 调用第一步中创建好的实例的execute 方法来执行第二步中创建好的GetMethod 实例4. 释放连接。
无论执行方法是否成功,都必须释放连接5. 对得到后的内容进行处理注意在第五步的时候存在着三种取得目标内容的方法:1. getResponseBody,该方法返回的是目标的二进制的byte流;2. getResponseBodyAsString,这个方法返回的是String类型;3. getResponseBodyAsStream,这个方法对于目标地址中有大量数据需要传输;具体情况根据实际情况而定.附上访问网易首页的的代码:import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import mons.httpclient.DefaultHttpMethodRetryHandler;import mons.httpclient.HttpClient;import mons.httpclient.HttpException;import mons.httpclient.HttpStatus;import mons.httpclient.methods.GetMethod;import mons.httpclient.params.HttpMethodParams;public class GetSample {/**采用数据流的方式读取页面数据,最后以字符串的形式呈现。
org.apache.http.client.HttpClient使⽤⽅法⼀.官⽹说明:Commons HttpClient项⽬现已结束,不再开发。
它已被其HttpClient和HttpCore模块中的Apache HttpComponents项⽬所取代,它们提供更好的性能和更⼤的灵活性。
从2011年开始,mons.httpclient就不再开发。
这就是说,它已经落伍了。
⽅法的对称性上的区别⼀、org.apache.http.clientorg.apache.http.client在发起请求前,假如对某个参数a 进⾏url encode编码。
服务端必须进⾏url decode。
//客户端编码Stirng a=URLEncoder.encode(cont,"GBK");//服务端解码URLDecoder.decode(a,"gbk");且服务器端获取到的参数a为可识别的没有任何变动的url encode后原值。
⼆、mons.httpclientmons.httpclient则与之相反。
服务端获取到的a为不可识别的乱码,且不能⽤url decode解码。
//服务端解码new String(cont.getBytes("ISO8859_1"), "GBK")与时俱进org.apache.http.client更好的性能和更⼤的灵活性。
三.pom.xml<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency><!-- https:///artifact/org.jsoup/jsoup --><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.11.3</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.1</version></dependency>最最简单的⽅法利⽤Jsoup直接获取HTML页⾯Document doc = Jsoup.connect("/xiaoshuodaquan/").get(); Elements elements = doc.getElementsContainingOwnText("⽃破苍穹");四.简单使⽤⽅法package com.feilong.reptile.util;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.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.util.ArrayList;import java.util.List;import mons.codec.Charsets;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import ValuePair;public class MHttpClient {public void get(String url) throws Exception {// 创建HttpClient实例HttpClient client = HttpClientBuilder.create().build();// 根据URL创建HttpGet实例HttpGet get = new HttpGet(url);// 执⾏get请求,得到返回体HttpResponse response = client.execute(get);// 判断是否正常返回if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 解析数据String data = EntityUtils.toString(response.getEntity(),Charsets.UTF_8); System.out.println(data);}}public void post(String url) throws Exception {// 创建HttpClient实例HttpClient client = HttpClientBuilder.create().build();// 根据URL创建HttpPost实例HttpPost post = new HttpPost(url);// 构造post参数List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("name", "11"));// 编码格式转换UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);// 传⼊请求体post.setEntity(entity);// 发送请求,得到响应体HttpResponse response = client.execute(post);// 判断是否正常返回if (response.getStatusLine().getStatusCode() == 200) {// 解析数据HttpEntity resEntity = response.getEntity();String data = EntityUtils.toString(resEntity);System.out.println(data);}}public static void main(String[] args) throws Exception {MHttpClient cl = new MHttpClient();String url = "/xiaoshuodaquan/";cl.get(url);}}六. 复杂使⽤⽅法package com.feilong.reptile.util;import java.io.IOException;import java.io.InterruptedIOException;import .UnknownHostException;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import .ssl.SSLException;import mons.codec.Charsets;import org.apache.http.Header;import org.apache.http.HttpEntityEnclosingRequest;import org.apache.http.HttpRequest;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.HttpRequestRetryHandler;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.protocol.HttpClientContext;import org.apache.http.client.utils.URIBuilder;import org.apache.http.config.SocketConfig;import org.apache.http.conn.ConnectTimeoutException;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.protocol.HttpContext;import org.apache.http.util.EntityUtils;/*** 使⽤HttpClient发送和接收Http请求** @author manzhizhen**/public class HttpUtils {private static HttpClient httpClient;// 最⼤连接数private static final int MAX_CONNECTION = 100;// 每个route能使⽤的最⼤连接数,⼀般和MAX_CONNECTION取值⼀样private static final int MAX_CONCURRENT_CONNECTIONS = 100;// 建⽴连接的超时时间,单位毫秒private static final int CONNECTION_TIME_OUT = 1000;// 请求超时时间,单位毫秒private static final int REQUEST_TIME_OUT = 1000;// 最⼤失败重试次数private static final int MAX_FAIL_RETRY_COUNT = 3;// 请求配置,可以复⽤private static RequestConfig requestConfig;static {SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(REQUEST_TIME_OUT).setSoKeepAlive(true).setTcpNoDelay(true).build();requestConfig = RequestConfig.custom().setSocketTimeout(REQUEST_TIME_OUT).setConnectTimeout(CONNECTION_TIME_OUT).build();/*** 每个默认的 ClientConnectionPoolManager 实现将给每个route创建不超过2个并发连接,最多20个连接总数。
Java httpclient解决方案中的中文传递(2009-03-05 17:21:33)标签:杂谈1 Commons HttpClient 开源项目简介Http 协议是一种应用十分广泛的网络应用层协议。
在Java 网络编程中我们会经常碰到Http 协议编程, 虽然JDK 提供了HttpURLConnection 编程接口对Http 协议进行支持, 但是由于协议应用本身的复杂性, 使得在大量实际项目单纯使用JDK 进行Http编程仍然相对比较困难。
针对这种情况, 开源软件组织Apach 推出了HttpClient 开源组件, 并且提供稳定持续的升级版本, 因此在实际项目中采用HttpClient 组件进行Http 协议编程是一种高效经济的解决方案。
2 Commons HttpClient 中文环境下编程常见问题由于HttpClient 组件设计的高度灵活性及易用性, 应用HttpClient 组件进行编程本身并不复杂。
但是由于Java 编程环境自身容易出现字符编码问题, 衍生于Java 语言并主要由英语语系国家技术人员推出的HttpClient 组件自然在中文环境中会存在一定的编码问题, 同时由于部分Web 浏览器及Web 服务器并未严格实现标准Http 协议规范, 使得比较严格遵循标准Http 协议规范的Http-Client 组件在与部分浏览器及服务器进行交互时会出现少量兼容性问题。
笔者在中文环境下用HttpClinet 开发校外资源访问系统的过程中碰到系列HttpClient 技术问题, 经过测试查证找到相应的解决办法, 这对解决HttpClient 编程问题, 特别是中文环境下Http-Client 编程具有较大的借鉴作用。
( 注: 本文编程的HttpClient 组件版本为: Release 3.1 Beta 1)3 Commons HttpClient 编程的典型问题及解决办法3.1 URL 中文参数无法识别的问题通常情况在Commons HttpClient 编程中我们用下列语句就可以向一个目标服务器提交一个Web 请求:HttpClient client=new HttpClient();GetMethod method = new GetMethod (url);//本示例使用Get 方法, 当然也可使用Post 方法PostMethod method//=new PostMethod(url);client.executeMethod(method);InputStream receiver=method.getResponseBodyAsStream();如果URL 没有中文参数,以上语句执行起来没有任何问题,但是如果URL 中含有中文字符,中文参数将无法被Web 服务器识别, 程序虽然可以正常运行, 但却无法得到正确结果。
(精华)2020年9⽉13⽇C#基础知识点⽹络编程HttpClient详解(精华)2020年9⽉13⽇ C#基础知识点⽹络编程HttpClient详解⼀、HttpClient⽤法HttpClient 提供的⽅法:GetAsync(String) //以异步操作将GET请求发送给指定的URIGetAsync(URI) //以异步操作将GET请求发送给指定的URIGetAsync(String, HttpCompletionOption) //以异步操作的HTTP完成选项发送GET请求到指定的URIGetAsync(String, CancellationToken) //以异步操作的取消标记发送GET请求到指定URIGetAsync(Uri, HttpCompletionOption) //以异步操作的HTTP完成选项发送GET请求到指定的URIGetAsync(Uri, HttpCompletionOption, CancellationToken) //以异步操作的HTTP完成选项和取消标记发送DELETE请求到指定的URIGetAsync(Uri, HttpCompletionOption, CancellationToken) //以异步操作的HTTP完成选项和取消标记发送DELETE请求到指定的URIGetByteArrayAsync(String) //将GET请求发送到指定URI并在异步操作中以字节数组的形式返回响应正⽂GetByteArrayAsync(Uri) //将GET请求发送到指定URI并在⼀异步操作中以字节数组形式返回响应正⽂GetHashCode //⽤作特定类型的哈希函数,继承⾃ObjectGetStreamAsync(String) //将GET请求发送到指定URI并在异步操作中以流的形式返回响应正⽂GetStreamAsync(Uri) //将GET请求发送到指定URI并在异步操作以流的形式返回响应正⽂GetStreamAsync(String) //将GET请求发送到指定URI并在异步操作中以字符串的形式返回响应正⽂GetStringAsync(Uri) //将GET请求发送到指定URI并在异步操作中以字符串形式返回响应正⽂using(var httpClient = new HttpClient()){<!-- -->//other codes}以上⽤法是不推荐的,HttpClient 这个对象有点特殊,虽然继承了 IDisposable 接⼝,但它是可以被共享的(或者说可以被复⽤),且线程安全。
HttpClient 教程前言超文本传输协议(HTTP)也许是当今互联网上使用的最重要的协议了。
Web服务,有网络功能的设备和网络计算的发展,都持续扩展了HTTP协议的角色,超越了用户使用的Web浏览器范畴,同时,也增加了需要HTTP协议支持的应用程序的数量。
尽管包提供了基本通过HTTP访问资源的功能,但它没有提供全面的灵活性和其它很多应用程序需要的功能。
HttpClient就是寻求弥补这项空白的组件,通过提供一个有效的,保持更新的,功能丰富的软件包来实现客户端最新的HTTP标准和建议。
为扩展而设计,同时为基本的HTTP协议提供强大的支持,HttpClient组件也许就是构建HTTP客户端应用程序,比如web浏览器,web服务端,利用或扩展HTTP协议进行分布式通信的系统的开发人员的关注点。
1. HttpClient的范围∙基于HttpCore[/httpcomponents-core/index.html]的客户端HTTP运输实现库∙基于经典(阻塞)I/O∙内容无关2. 什么是HttpClient不能做的∙HttpClient不是一个浏览器。
它是一个客户端的HTTP通信实现库。
HttpClient 的目标是发送和接收HTTP报文。
HttpClient不会去缓存内容,执行嵌入在HTML页面中的javascript代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和HTTP运输无关的功能。
第一章基础1.1 执行请求HttpClient最重要的功能是执行HTTP方法。
一个HTTP方法的执行包含一个或多个HTTP请求/HTTP响应交换,通常由HttpClient的内部来处理。
而期望用户提供一个要执行的请求对象,而HttpClient期望传输请求到目标服务器并返回对应的响应对象,或者当执行不成功时抛出异常。
很自然地,HttpClient API的主要切入点就是定义描述上述规约的HttpClient接口。
HttpClient ⼊门教程学习HttpClient 简介HttpClient 是基于HttpCore 的兼容的HTTP 代理实现。
它还为客户端认证,HTTP 状态管理和HTTP 连接管理提供可重⽤组件。
HttpComponents Client 是Commons HttpClient 3.x 的继任者和替代者。
强烈建议Commons HttpClient 的⽤户进⾏升级。
HttpClient HTTP Get 请求HttpClient HTTP Post 请求HTTP/1.1/*** httpClient Get 请求*/public static void main(String[] args) throws IOException {try (CloseableHttpClient httpclient = HttpClients.createDefault()) {//第⼀步 配置 Get 请求 UrlHttpGet httpget = new HttpGet("/get"); //第⼆步 创建⼀个⾃定义的 response handlerResponseHandler<String> responseHandler = new ResponseHandler<String>() {@Overridepublic String handleResponse(HttpResponse response) throws IOException {int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status); } }};//第三步 执⾏请求 String responseBody = httpclient.execute(httpget, responseHandler);System.out.println("----------------------------------------");System.out.println(responseBody);}}/*** httpClient Post 请求 */public static void main(String[] args) throws IOException {try (CloseableHttpClient httpclient = HttpClients.createDefault()) {//第⼀步 配置 Post 请求 UrlHttpPost httpPost = new HttpPost("/post");// 装配post 请求参数List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); list.add(new BasicNameValuePair("age", "20")); //请求参数list.add(new BasicNameValuePair("name", "zhangsan")); //请求参数httpPost.setEntity(new StringEntity("Hello, World"));/*设置post 请求参数两个⽅式:具体参考UrlEncodedFormEntity 和StringEntity 区别*/httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); //httpPost.setEntity(new StringEntity(list.toString(), "UTF-8")); //第⼆步 创建⼀个⾃定义的 response handlerResponseHandler<String> responseHandler = new ResponseHandler<String>() {@Overridepublic String handleResponse(HttpResponse response) throws IOException {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status);}}};};//第三步执⾏请求String responseBody = httpclient.execute(httpPost, responseHandler);System.out.println("----------------------------------------");System.out.println(responseBody);}}HttpClient HTTP Put请求/*** httpClient Put 请求*/public static void main(String[] args) throws IOException {try (CloseableHttpClient httpclient = HttpClients.createDefault()) {//第⼀步配置 Post 请求 UrlHttpPut httpPut = new HttpPut("/put");//设置post请求参数httpPut.setEntity(new StringEntity("Hello, World"));//第⼆步创建⼀个⾃定义的 response handlerResponseHandler<String> responseHandler = new ResponseHandler<String>() {@Overridepublic String handleResponse(HttpResponse response) throws IOException {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status); }}};String responseBody = httpclient.execute(httpPut, responseHandler);System.out.println("----------------------------------------");System.out.println(responseBody);}}HttpClient HTTP Delete请求/*** httpClient Delete 请求*/public static void main(String[] args) throws IOException {try (CloseableHttpClient httpclient = HttpClients.createDefault()) {//第⼀步配置 Delete 请求 UrlHttpDelete httpDelete = new HttpDelete("/delete");System.out.println("Executing request " + httpDelete.getRequestLine());//第⼆步创建⼀个⾃定义的 response handlerResponseHandler<String> responseHandler = new ResponseHandler<String>() {@Overridepublic String handleResponse(HttpResponse response) throws IOException {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status); }}};String responseBody = httpclient.execute(httpDelete, responseHandler);System.out.println("----------------------------------------");System.out.println(responseBody);}}HttpClient⾃定义HTTP Header/*** HttpClient⾃定义HTTP头*/public static void main(String[] args)throws IOException {// 创建⾃定义 http headersList<Header> defaultHeaders = Arrays.asList(new BasicHeader("X-Default-Header", "default header httpclient"));// 设置⾃定义 http headersCloseableHttpClient httpclient = HttpClients.custom().setDefaultHeaders(defaultHeaders).build();try {// 配置超时时间RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) //设置连接超时时间.setConnectionRequestTimeout(5000) // 设置请求超时时间.setSocketTimeout(5000).setRedirectsEnabled(true)//默认允许⾃动重定向.build();// 创建⾃定义 http headers on the http requestHttpUriRequest request = RequestBuilder.get().setUri("/headers").setHeader(HttpHeaders.CONTENT_TYPE, "application/json").setHeader(HttpHeaders.FROM, "https://").setHeader("X-Custom-Header", "custom header http request").setConfig(requestConfig).build();System.out.println("Executing request " + request.getRequestLine());// 创建⾃定义 response handlerResponseHandler<String> responseHandler = response -> {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status); }};String responseBody = httpclient.execute(request, responseHandler);System.out.println("----------------------------------------");System.out.println(responseBody);} finally {httpclient.close();}}更详细HttpClient 学习。
HttpClient⽤法--这⼀篇全了解(内含例⼦)HttpClient相⽐传统JDK⾃带的URLConnection,增加了易⽤性和灵活性,它不仅使客户端发送Http请求变得容易,⽽且也⽅便开发⼈员测试接⼝(基于Http协议的),提⾼了开发的效率,也⽅便提⾼代码的健壮性。
因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深⼊。
mons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别Commons的HttpClient项⽬现在是⽣命的尽头,不再被开发, 已被Apache HttpComponents项⽬HttpClient和HttpCore 模组取代,提供更好的性能和更⼤的灵活性。
⼀、简介HttpClient是Apache Jakarta Common下的⼦项⽬,⽤来提供⾼效的、最新的、功能丰富的⽀持HTTP协议的客户端编程⼯具包,并且它⽀持HTTP协议最新的版本和建议。
HttpClient已经应⽤在很多的项⽬中,⽐如Apache Jakarta上很著名的另外两个开源项⽬Cactus和HTMLUnit都使⽤了HttpClient。
⼆、特性1. 基于标准、纯净的java语⾔。
实现了Http1.0和Http1.12. 以可扩展的⾯向对象的结构实现了Http全部的⽅法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. ⽀持HTTPS协议。
4. 通过Http代理建⽴透明的连接。
5. 利⽤CONNECT⽅法通过Http代理建⽴隧道的https连接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证⽅案。
7. 插件式的⾃定义认证⽅案。
8. 便携可靠的套接字⼯⼚使它更容易的使⽤第三⽅解决⽅案。
Package‘onsr’October14,2022Title Client for the'ONS'APIVersion1.0.1Description Client for the'Office of National Statistics'('ONS')API<https:///v1>.License GPL(>=3)Encoding UTF-8LazyData trueImports httr,jsonlite,readr,tibbleURL https://kvasilopoulos.github.io/onsr/BugReports https:///kvasilopoulos/onsr/issuesRoxygenNote7.1.1Suggests testthat(>=3.0.0),data.table,vroom,curlConfig/testthat/edition3Depends R(>=2.10)NeedsCompilation noAuthor Kostas Vasilopoulos[aut,cre]Maintainer Kostas Vasilopoulos<***********************>Repository CRANDate/Publication2022-01-2120:22:43UTCR topics documented:ons_browse (2)ons_browse_qmi (2)ons_codelists (3)ons_codes (4)ons_datasets (5)ons_desc (5)ons_extra (6)12ons_browse_qmi ons_get (7)ons_latest (8)ons_search (9)Index10 ons_browse Quickly browse to ONS’developer webpageDescriptionThis function take you to the ONS’developer webpage.Usageons_browse()ValueAn atomic character vector with the url of the webpageExamplesons_browse()ons_browse_qmi Quickly browse to dataset’s Quality and Methodology Information(QMI)DescriptionThis function take you to the QMI.Usageons_browse_qmi(id=NULL)Argumentsid[character]Id that represents a dataset.ValueAn atomic character vector url with of the webpageons_codelists3 Examplesons_browse_qmi("cpih01")ons_codelists Explore codes and listsDescriptionUsed to get details about codes and code lists stored by ONS.Codes are used to provide a common definition when presenting statistics with related categories.Codes are gathered in code lists,which may change over time to include new or different codes.The meaning of a code should not change over time,but new codes may be created where new meaning is required.Usageons_codelists()ons_codelist(code_id=NULL)ons_codelist_editions(code_id=NULL)ons_codelist_edition(code_id=NULL,edition=NULL)Argumentscode_id[character].The id of a codelist.edition[character]A subset of the dataset representing a specific time period.For some datasets this edition can contain all time periods(all historical data).Thelatest version of this is displayed by default.ValueA list or character vector.Examplesons_codelists()ons_codelist(code_id="quarter")#editionsons_codelist_editions(code_id="quarter")ons_codelist_edition(code_id="quarter",edition="one-off")4ons_codes ons_codes Explore codes and listsDescriptionUsed to get details about codes and code lists stored by ONS.Codes are used to provide a common definition when presenting statistics with related categories.Codes are gathered in code lists,which may change over time to include new or different codes.The meaning of a code should not change over time,but new codes may be created where new meaning is required.Usageons_codes(code_id=NULL,edition=NULL)ons_code(code_id=NULL,edition=NULL,code=NULL)ons_code_dataset(code_id=NULL,edition=NULL,code=NULL)Argumentscode_id[character].The id of a codelist.edition[character]A subset of the dataset representing a specific time period.For some datasets this edition can contain all time periods(all historical data).Thelatest version of this is displayed by default.code[character]The ID of the code within a code list.ValueA list or character vector.Examples#codesons_codes(code_id="quarter",edition="one-off")ons_code(code_id="quarter",edition="one-off",code="q2")ons_code_dataset(code_id="quarter",edition="one-off",code="q2")ons_datasets5 ons_datasets ONS DatasetsDescriptionA grouping of data(editions)with shared dimensions,for example Sex,Age and Geography,and allpublished history of this group of data.The options in these dimensions can change over time lead-ing to separate editions.For example:Population Estimates for UK,England and Wales,Scotland and Northern Ireland.Usageons_datasets()ons_ids()ValueA tibble with the datasets.Examples#Find all the information about the dataons_datasets()#Just the idsons_ids()ons_desc Description of the DatasetDescriptionThis function provides a description of the important information about a dataset.Usageons_desc(id=NULL)Argumentsid[character]Id that represents a dataset.6ons_extraValueA description of the requested dataset.See Alsoons_meta()Examplesons_desc("cpih01")ons_extra Access dataset’s additional informationDescriptionData in each version is broken down by dimensions,and a unique combination of dimension options in a version can be used to retrieve observation level data.Usageons_dim(id=NULL,edition=NULL,version=NULL)ons_dim_opts(id=NULL,edition=NULL,version=NULL,dimension=NULL,limit=NULL,offset=NULL)ons_meta(id=NULL,edition=NULL,version=NULL)Argumentsid[character]Id that represents a dataset.edition[character]A subset of the dataset representing a specific time period.For some datasets this edition can contain all time periods(all historical data).Thelatest version of this is displayed by default.version[character]A specific instance of the edition at a point in time.New versions can be published as a result of corrections,revisions or new data becoming avail-able.dimension[character]ons_get7 limit[numeric(1):NULL]Number of records to return.By default is NULL,which means that the defaults of the ONS API are used.You can set it to a number torequest more(or less)records,and also to Inf to request all records.offset[numeric(1):NULL]The position in the dataset of a particular record.By specifying offset,you retrieve a subset of records starting with the offsetvalue.Offset normally works with length,which determines how many recordsto retrieve starting from the offset.ValueA character vector.Examplesons_dim(id="cpih01")ons_dim_opts(id="cpih01",dimension="time")ons_meta(id="cpih01")ons_get Download data from ONSDescriptionThis functions is used tofind information about data published by the ONS.Datasets are published in unique versions,which are categorized by edition.Available datasets are given an id.All available id can be viewed with ons_ids().Usageons_get(id=NULL,edition=NULL,version=NULL,ons_read=getOption("onsr.read"),...)ons_get_obs(id=NULL,edition=NULL,version=NULL,...)Argumentsid[character]Id that represents a dataset.edition[character]A subset of the dataset representing a specific time period.For some datasets this edition can contain all time periods(all historical data).Thelatest version of this is displayed by default.8ons_latest version[character]A specific instance of the edition at a point in time.New versions can be published as a result of corrections,revisions or new data becoming avail-able.ons_read[character].Reading backend,one of readr,data.table or vroom....Further arguments passed on the methods.ValueA tibble with the dataset in tidy format.Examplesons_get(id="cpih01")#Same dataset but older versionons_get(id="cpih01",version="5")#Take only specific observationsons_get_obs("cpih01",geography="K02000001",aggregate="cpih1dim1A0",time="Oct-11") #Or can use a wildcard for the timeons_get_obs("cpih01",geography="K02000001",aggregate="cpih1dim1A0",time="*")ons_latest Latest info on ONS DatasetsDescriptionThis functions are used to access the latest href,version and edition of a dataset.Usageons_latest_href(id=NULL)ons_latest_version(id=NULL)ons_latest_edition(id=NULL)Argumentsid[character]Id that represents a dataset.ons_search9ValueAn atomic character vector with the latest info.Examplesons_latest_href("cpih01")ons_latest_version("cpih01")ons_latest_edition("cpih01")ons_search Search for a DatasetDescriptionSearch for a DatasetUsageons_search(id,edition=NULL,version=NULL,name=NULL,query=NULL)Argumentsid[character]Id that represents a dataset.edition[character]A subset of the dataset representing a specific time period.For some datasets this edition can contain all time periods(all historical data).Thelatest version of this is displayed by default.version[character]A specific instance of the edition at a point in time.New versions can be published as a result of corrections,revisions or new data becoming avail-able.name[character].The name of dimension to perform the query.Available dimen-sions for a specific id at ons_dim().query[character].The query.ValueA data.frame.Examplesons_dim("cpih01")ons_search("cpih01",name="aggregate",query="cpih1dim1A0")Indexons_browse,2ons_browse_qmi,2ons_code(ons_codes),4ons_code_dataset(ons_codes),4ons_codelist(ons_codelists),3ons_codelist_edition(ons_codelists),3ons_codelist_editions(ons_codelists),3ons_codelists,3ons_codes,4ons_datasets,5ons_desc,5ons_dim(ons_extra),6ons_dim_opts(ons_extra),6ons_extra,6ons_get,7ons_get_obs(ons_get),7ons_ids(ons_datasets),5ons_latest,8ons_latest_edition(ons_latest),8ons_latest_href(ons_latest),8ons_latest_version(ons_latest),8ons_meta(ons_extra),6ons_search,910。
httpclient教程Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。
1.读取网页(HTTP/HTTPS)内容最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面Java代码1.package http.demo;2.3.import java.io.IOException;4.import mons.httpclient.*;5.import mons.httpclient.methods.*;6.7.public class SimpleClient {8.9. public static void main(String[] args) throws IOException10. {11. HttpClient client = new HttpClient();12.13. //设置代理服务器地址和端口14.15. //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);16.17. //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https18.19. HttpMethod method = new GetMethod("");20.21. //使用POST方法22.23. //HttpMethod method = new PostMethod("http://java.sun.com");24.25. client.executeMethod(method);26.27. //打印服务器返回的状态28.29. System.out.println(method.getStatusLine());30.31. //打印返回的信息32.33. System.out.println(method.getResponseBodyAsString());34.35. //释放连接36.37. method.releaseConnection();38.39. }40.}2.以GET或者POST方式向网页提交参数Java代码1.package http.demo;2.3.import java.io.IOException;4.5.import mons.httpclient.*;6.7.import mons.httpclient.methods.*;8.9./**10.11.* 提交参数演示12.13.* 该程序连接到一个用于查询手机号码所属地的页面14.15.* 以便查询号码段1330227所在的省份以及城市16.17.*/18.19.public class SimpleHttpClient {20.21. public static void main(String[] args) throws IOException23. {24.25. HttpClient client = new HttpClient();26.27. client.getHostConfiguration().setHost(".cn", 80, "http");28.29. HttpMethod method = getPostMethod();//使用POST方式提交数据30.31. client.executeMethod(method);32.33. //打印服务器返回的状态34.35. System.out.println(method.getStatusLine());36.37. //打印结果页面38.39. String response =40.41. new String(method.getResponseBodyAsString().getBytes("8859_1"));42.43. //打印返回的信息44.45. System.out.println(response);46.47. method.releaseConnection();48.49. }50.51. /**52.53. * 使用GET方式提交数据54.55. * @return56.57. */58.59. private static HttpMethod getGetMethod(){60.61. return new GetMethod("/simcard.php?simcard=1330227");63. }64.65. /**66.67. * 使用POST方式提交数据68.69. * @return70.71. */72.73. private static HttpMethod getPostMethod(){74.75. PostMethod post = new PostMethod("/simcard.php");76.77. NameValuePair simcard = new NameValuePair("simcard","1330227");78.79. post.setRequestBody(new NameValuePair[] { simcard});80.81. return post;82.83. }84.85.}3.处理页面重定向详细描述:状态码对应HttpServletResponse的常量301 SC_MOVED_PERMANENTLY 页面已经永久移到另外一个新地址302 SC_MOVED_TEMPORARILY 页面暂时移动到另外一个新的地址303 SC_SEE_OTHER 客户端请求的地址必须通过另外的URL来访问307 SC_TEMPORARY_REDIRECT 同 SC_MOVED_TEMPORARILY下面的代码片段演示如何处理页面的重定向Java代码1.client.executeMethod(post);2.3.System.out.println(post.getStatusLine().toString());4.5.post.releaseConnection();6.7.//检查是否重定向8.9.int statuscode = post.getStatusCode();10.11.if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||12.13. (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||14.15. (statuscode == HttpStatus.SC_SEE_OTHER) ||16.17. statuscode == HttpStatus.SC_TEMPORARY_REDIRECT))18.19.20. //读取新的URL地址21.22. Header header = post.getResponseHeader("location");23.24. if (header != null)25. {26.27. String newuri = header.getValue();28.29. if ((newuri == null) || (newuri.equals("")))30.31. newuri = "/";32.33.34. GetMethod redirect = new GetMethod(newuri);35.36. client.executeMethod(redirect);37.38. System.out.println("Redirect:"+39. redirect.getStatusLine().toString());40.41. redirect.releaseConnection();42.43. } else44.45. System.out.println("Invalid redirect");46.47. }4.模拟输入用户名和口令进行登录本小节应该说是HTTP客户端编程中最常碰见的问题,很多网站的内容都只是对注册用户可见的,这种情况下就必须要求使用正确的用户名和口令登录成功后,方可浏览到想要的页面。
HttpClient详细使⽤⽰例详解⽬录进⼊正题详细使⽤⽰例HttpClient 是Apache Jakarta Common 下的⼦项⽬,可以⽤来提供⾼效的、最新的、功能丰富的⽀持 HTTP 协议的客户端编程⼯具包,并且它⽀持 HTTP 协议最新的版本和建议。
HTTP 协议可能是现在 Internet 上使⽤得最多、最重要的协议了,越来越多的 Java 应⽤程序需要直接通过 HTTP 协议来访问⽹络资源。
虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于⼤部分应⽤程序来说,JDK 库本⾝提供的功能还不够丰富和灵活。
HttpClient 是 Apache Jakarta Common 下的⼦项⽬,⽤来提供⾼效的、最新的、功能丰富的⽀持 HTTP 协议的客户端编程⼯具包,并且它⽀持 HTTP 协议最新的版本和建议。
HTTP和浏览器有点像,但却不是浏览器。
很多⼈觉得既然HttpClient是⼀个HTTP客户端编程⼯具,很多⼈把他当做浏览器来理解,但是其实HttpClient不是浏览器,它是⼀个HTTP通信库,因此它只提供⼀个通⽤浏览器应⽤程序所期望的功能⼦集,最根本的区别是HttpClient中没有⽤户界⾯,浏览器需要⼀个渲染引擎来显⽰页⾯,并解释⽤户输⼊,例如⿏标点击显⽰页⾯上的某处,有⼀个布局引擎,计算如何显⽰HTML页⾯,包括级联样式表和图像。
javascript解释器运⾏嵌⼊HTML页⾯或从HTML页⾯引⽤的javascript代码。
来⾃⽤户界⾯的事件被传递到javascript解释器进⾏处理。
除此之外,还有⽤于插件的接⼝,可以处理Applet,嵌⼊式媒体对象(如pdf⽂件,Quicktime电影和Flash动画)或ActiveX控件(可以执⾏任何操作)。
HttpClient只能以编程的⽅式通过其API⽤于传输和接受HTTP消息。
HttpClient的主要功能:实现了所有 HTTP 的⽅法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)⽀持 HTTPS 协议⽀持代理服务器(Nginx等)等⽀持⾃动(跳转)转向……进⼊正题环境说明:JDK1.8、SpringBoot准备环节第⼀步:在pom.xml中引⼊HttpClient的依赖第⼆步:引⼊fastjson依赖注:本⼈引⼊此依赖的⽬的是,在后续⽰例中,会⽤到“将对象转化为json字符串的功能”,也可以引其他有此功能的依赖。
HttpClient提供URIBuilder工具类来简化URIs的创建和修改过程。
1. URI uri = new URIBuilder()2. .setScheme("http")3. .setHost("")4. .setPath("/search")5. .setParameter("q", "httpclient")6. .setParameter("btnG", "Google Search")7. .setParameter("aq", "f")8. .setParameter("oq", "")9. .build();10. HttpGet httpget = new HttpGet(uri);11. System.out.println(httpget.getURI());上述代码会在控制台输出:1. /search?q=httpclient&btnG=Google+Search&aq=f&oq=1.1.2. HTTP响应服务器收到客户端的http请求后,就会对其进行解析,然后把响应发给客户端,这个响应就是HTTP response.HTTP响应第一行是协议版本,之后是数字状态码和相关联的文本段。
1. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,2. HttpStatus.SC_OK, "OK");3.4. System.out.println(response.getProtocolVersion());5. System.out.println(response.getStatusLine().getStatusCode());6. System.out.println(response.getStatusLine().getReasonPhrase());7. System.out.println(response.getStatusLine().toString());上述代码会在控制台输出:1. HTTP/1.12. 2003. OK4. HTTP/1.1 200 OK1.1.3. 消息头一个Http消息可以包含一系列的消息头,用来对http消息进行描述,比如消息长度,消息类型等等。
HttpClient介绍和简单使⽤流程HttpClientSpringCloud中服务和服务之间的调⽤全部是使⽤HttpClient,还有前⾯使⽤SolrJ中就封装了HttpClient,在调⽤SolrTemplate的saveBean ⽅法时就调⽤HttpClient技术。
当前⼤部分项⽬暴漏出来的接⼝是Http请求,数据格式是JSON格式,但在⼀些⽼项⽬使⽤的仍然是webService。
HttpClient 提供的主要的功能(1)实现了所有 HTTP 的⽅法(GET,POST,PUT,DELETE 等)(2)⽀持⾃动转向(3)⽀持 HTTPS 协议(4)⽀持代理服务器等1、关于Http的请求类型(常见)get、put、post、delete含义与区别1、GET请求会向数据库发索取数据的请求,从⽽来获取信息,该请求就像数据库的select操作⼀样,只是⽤来查询⼀下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产⽣副作⽤。
⽆论进⾏多少次操作,结果都是⼀样的。
2、与GET不同的是,PUT请求是向服务器端发送数据的,从⽽改变信息,该请求就像数据库的update操作⼀样,⽤来修改数据的内容,但是不会增加数据的种类等,也就是说⽆论进⾏多少次PUT操作,其结果并没有不同。
3、POST请求同PUT请求类似,都是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作⼀样,会创建新的内容。
⼏乎⽬前所有的提交操作都是⽤POST请求的。
4、DELETE请求顾名思义,就是⽤来删除某⼀个资源的,该请求就像数据库的delete操作。
就像前⾯所讲的⼀样,既然PUT和POST操作都是向服务器端发送数据的,那么两者有什么区别呢。
POST主要作⽤在⼀个集合资源之上的(url),⽽PUT主要作⽤在⼀个具体资源之上的(url/xxx),通俗⼀下讲就是,如URL可以在客户端确定,那么可使⽤PUT,否则⽤POST。
httpclient使用详解Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。
因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
一、简介HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
下载地址: /downloads.cgi二、特性1. 基于标准、纯净的Java语言。
实现了Http1.0和Http1.12. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支持HTTPS协议。
4. 通过Http代理建立透明的连接。
5. 利用CONNECT方法通过Http代理建立隧道的https连接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。
支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理Set-Cookie中的Cookie。
11. 插件式的自定义Cookie策略。
comons_httpClient教程Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。
1.读取网页(HTTP/HTTPS)内容最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面Java代码1.package http.demo;2.3.import java.io.IOException;4.import mons.httpclient.*;5.import mons.httpclient.methods.*;6.7.public class SimpleClient {8.9. public static void main(String[] args) throws IOException10. {11. HttpClient client = new HttpClient();12.13. //设置代理服务器地址和端口14.15. //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);16.17. //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https18.19. HttpMethod method = new GetMethod("");20.21. //使用POST方法22.23. //HttpMethod method = new PostMethod("http://java.sun.com");24.25. client.executeMethod(method);26.27. //打印服务器返回的状态28.29. System.out.println(method.getStatusLine());30.31. //打印返回的信息32.33. System.out.println(method.getResponseBodyAsString());34.35. //释放连接36.37. method.releaseConnection();38.39. }40.}2.以GET或者POST方式向网页提交参数Java代码1.package http.demo;2.3.import java.io.IOException;4.5.import mons.httpclient.*;6.7.import mons.httpclient.methods.*;8.9./**10.11.* 提交参数演示12.13.* 该程序连接到一个用于查询手机号码所属地的页面14.15.* 以便查询号码段1330227所在的省份以及城市16.17.*/18.19.public class SimpleHttpClient {20.21. public static void main(String[] args) throws IOException22.24.25. HttpClient client = new HttpClient();26.27. client.getHostConfiguration().setHost(".cn", 80,"http");28.29. HttpMethod method = getPostMethod();//使用POST方式提交数据30.31. client.executeMethod(method);32.33. //打印服务器返回的状态34.35. System.out.println(method.getStatusLine());36.37. //打印结果页面38.39. String response =40.41. new String(method.getResponseBodyAsString().getBytes("8859_1"));42.43. //打印返回的信息44.45. System.out.println(response);46.47. method.releaseConnection();48.49. }50.51. /**52.53. * 使用GET方式提交数据54.55. * @return56.57. */58.59. private static HttpMethod getGetMethod(){60.61. return new GetMethod("/simcard.php?simcard=1330227");62.64.65. /**66.67. * 使用POST方式提交数据68.69. * @return70.71. */72.73. private static HttpMethod getPostMethod(){74.75. PostMethod post = new PostMethod("/simcard.php");76.77. NameValuePair simcard = new NameValuePair("simcard","1330227");78.79. post.setRequestBody(new NameValuePair[] { simcard});80.81. return post;82.83. }84.85.}3.处理页面重定向详细描述:状态码对应HttpServletResponse的常量301 SC_MOVED_PERMANENTLY 页面已经永久移到另外一个新地址302 SC_MOVED_TEMPORARILY 页面暂时移动到另外一个新的地址303 SC_SEE_OTHER 客户端请求的地址必须通过另外的URL来访问307 SC_TEMPORARY_REDIRECT 同 SC_MOVED_TEMPORARILY下面的代码片段演示如何处理页面的重定向Java代码1.client.executeMethod(post);2.3.System.out.println(post.getStatusLine().toString());4.5.post.releaseConnection();6.7.//检查是否重定向8.9.int statuscode = post.getStatusCode();10.11.if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||12.13. (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||14.15. (statuscode == HttpStatus.SC_SEE_OTHER) ||16.17. statuscode == HttpStatus.SC_TEMPORARY_REDIRECT))18.19.20. //读取新的URL地址21.22. Header header = post.getResponseHeader("location");23.24. if (header != null)25. {26.27. String newuri = header.getValue();28.29. if ((newuri == null) || (newuri.equals("")))30.31. newuri = "/";32.33.34. GetMethod redirect = new GetMethod(newuri);35.36. client.executeMethod(redirect);37.38. System.out.println("Redirect:"+39. redirect.getStatusLine().toString());40.41. redirect.releaseConnection();42.43. } else44.45. System.out.println("Invalid redirect");46.47. }4.模拟输入用户名和口令进行登录本小节应该说是HTTP客户端编程中最常碰见的问题,很多网站的内容都只是对注册用户可见的,这种情况下就必须要求使用正确的用户名和口令登录成功后,方可浏览到想要的页面。
因为HTTP协议是无状态的,也就是连接的有效期只限于当前请求,请求内容结束后连接就关闭了。
在这种情况下为了保存用户的登录信息必须使用到Cookie机制。
以JSP/Servlet为例,当浏览器请求一个JSP 或者是Servlet的页面时,应用服务器会返回一个参数,名为jsessionid(因不同应用服务器而异),值是一个较长的唯一字符串的Cookie,这个字符串值也就是当前访问该站点的会话标识。
浏览器在每访问该站点的其他页面时候都要带上jsessionid这样的Cookie信息,应用服务器根据读取这个会话标识来获取对应的会话信息。
对于需要用户登录的网站,一般在用户登录成功后会将用户资料保存在服务器的会话中,这样当访问到其他的页面时候,应用服务器根据浏览器送上的Cookie中读取当前请求对应的会话标识以获得对应的会话信息,然后就可以判断用户资料是否存在于会话信息中,如果存在则允许访问页面,否则跳转到登录页面中要求用户输入帐号和口令进行登录。
这就是一般使用JSP开发网站在处理用户登录的比较通用的方法。
对于HTTP的客户端来讲,如果要访问一个受保护的页面时就必须模拟浏览器所做的工作,首先就是请求登录页面,然后读取Cookie值;再次请求登录页面并加入登录页所需的每个参数;最后就是请求最终所需的页面。
当然在除第一次请求外其他的请求都需要附带上 Cookie信息以便服务器能判断当前请求是否已经通过验证。
Java代码1.package http.demo;2.3.import mons.httpclient.*;4.5.import mons.httpclient.cookie.*;6.7.import mons.httpclient.methods.*;8.9./**10.11.* 用来演示登录表单的示例12.13.*/14.15.public class FormLoginDemo {16.17. static final String LOGON_SITE = "localhost";18.19. static final int LOGON_PORT = 8080;20.21.22.23. public static void main(String[] args) throws Exception{24.25. HttpClient client = new HttpClient();26.27. client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);28.29.30.31. //模拟登录页面login.jsp->main.jsp32.33. PostMethod post = new PostMethod("/main.jsp");34.35. NameValuePair name = new NameValuePair("name", "ld");36.37. NameValuePair pass = new NameValuePair("password", "ld");38.39. post.setRequestBody(new NameValuePair[]{name,pass});40.41. int status = client.executeMethod(post);42.43. System.out.println(post.getResponseBodyAsString());44.45. post.releaseConnection();46.47.48.49. //查看cookie信息50.51. CookieSpec cookiespec = CookiePolicy.getDefaultSpec();52.53. Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());54.55. if (cookies.length == 0) {56.57. System.out.println("None");58.59. } else {60.61. for (int i = 0; i < cookies.length; i++) {62.63. System.out.println(cookies[i].toString());64.65. }66.67. }68.69. //访问所需的页面main2.jsp70.71. GetMethod get = new GetMethod("/main2.jsp");72.73. client.executeMethod(get);74.75. System.out.println(get.getResponseBodyAsString());76.77. get.releaseConnection();78.79. }80.81.}5.提交XML格式参数提交XML格式的参数很简单,仅仅是一个提交时候的ContentType问题,下面的例子演示从文件文件中读取XML信息并提交给服务器的过程,该过程可以用来测试Web服务。