HttpClient教程
- 格式:docx
- 大小:79.53 KB
- 文档页数:39
HttpClient,DefaultHttpClient使⽤详解HttpClient:是⼀个接⼝⾸先需要先创建⼀个DefaultHttpClient的实例HttpClient httpClient=new DefaultHttpClient();发送GET请求:先创建⼀个HttpGet对象,传⼊⽬标的⽹络地址,然后调⽤HttpClient的execute()⽅法即可:httpClient.execute(httpGet);发送POST请求:创建⼀个HttpPost对象,传⼊⽬标的⽹络地址:通过⼀个NameValuePair集合来存放待提交的参数,并将这个参数集合传⼊到⼀个UrlEncodedFormEntity中,然后调⽤HttpPost的setEntity()⽅法将构建好的UrlEncodedFormEntity传⼊:List<NameValuePair>params=newArrayList<NameValuePair>();Params.add(new BasicNameValuePair(“username”,”admin”));Params.add(new BasicNameValuePair(“password”,”123456”));UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”);httpPost.setEntity(entity);调⽤HttpClient的execute()⽅法,并将HttpPost对象传⼊即可:HttpClient.execute(HttpPost);执⾏execute()⽅法之后会返回⼀个HttpResponse对象,服务器所返回的所有信息就保护在HttpResponse⾥⾯.先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了:If(httpResponse.getStatusLine().getStatusCode()==200){//请求和响应都成功了HttpEntityentity=HttpResponse.getEntity();//调⽤getEntity()⽅法获取到⼀个HttpEntity实例Stringresponse=EntityUtils.toString(entity,”utf-8”);//⽤EntityUtils.toString()这个静态⽅法将HttpEntity转换成字符串,防⽌服务器返回的数据带有中⽂,所以在转换的时候将字符集指定成utf-8就可以了}Http协议的重要性相信不⽤我多说了,HttpClient相⽐传统JDK⾃带的URLConnection,增加了易⽤性和灵活性(具体区别,⽇后我们再讨论),它不仅是客户端发送Http请求变得容易,⽽且也⽅便了开发⼈员测试接⼝(基于Http协议的),即提⾼了开发的效率,也⽅便提⾼代码的健壮性。
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对象。
目录HttpClient简介 (4)1)百科名片: (4)2)HttpClient 的范围 (4)3)httpClient 特性 (4)HttpClient基本功能的使用 (6)a)环境准备 (6)b)几个主要类解释 (6)c)第一个程序 (6)d)如何传递参数 (8)e)模拟表单登录 (10)f)HttpClient连接SSL (12)1)生成KeyStore (12)2)配置tomcat服务器支持SSL (13)3)用浏览器访问你的应用 (15)4)用httpClient访问https (15)HttpClient简介1)百科名片:HTTP 协议可能是现在Internet 上使用得最多、最重要的协议了,越来越多的Java 应用程序需要直接通过HTTP 协议来访问网络资源。
虽然在JDK 的java net包中已经提供了访问HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
HttpClient 是Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP 协议的客户端编程工具包,并且它支持HTTP 协议最新的版本和建议。
HttpClient 已经应用在很多的项目中,比如Apache Jakarta 上很著名的另外两个开源项目Cactus 和HTMLUnit 都使用了HttpClient。
现在HttpClient最新版本为HttpClient 4.1.2)HttpClient 的范围•基于HttpCore的客户端HTTP运输实现库•基于经典(阻塞)I/O•内容无关3)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.•源代码基于Apache License 可免费获取.HttpClient基本功能的使用a)环境准备•从apache下载httpClient;•下载地址: /downloads.cgi;•解压、将lib下的jar导入工程;b)几个主要类解释c)第一个程序d)如何传递参数e)模拟表单登录f)HttpClient连接SSL1)生成KeyStore打开cmd,输入(jdk环境变量当然是配置好的):keytool -genkey -alias tomcat -keyalg RSA –validity 60 -keystore D:\tomcat.keystorecmd输出:输入keystore密码:******您的名字与姓氏是什么?[Unknown]:localhost您的组织单位名称是什么?[Unknown]:it您的组织名称是什么?[Unknown]:dev您所在的城市或区域名称是什么?[Unknown]:bj您所在的州或省份名称是什么?[Unknown]:bj该单位的两字母国家代码是什么[Unknown]:CNCN=localhost, OU= it, O= dev, L=bj, ST=bj, C=CN 正确吗?[否]:Y输入的主密码(如果和keystore 密码相同,按回车):*******参数说明:-genkey表示生成密钥-validity指定证书有效期,这里是60天-alias指定别名,这里是tomcat-keyalg指定算法,这里是RSA-keystore指定存储位置,这里是D:\ tomcat.keystore使用的自定义密码为123456Keytool 详细命令说明请参考百度百科;*其中您的名字与姓氏是什么?localhost是网站的域名或者ip,根据实际情况填写。
使用HttpClient提交数据(一)HttpClient 是Apache Jakarta Common 下的子项目,提供了高效的、最新的、功能丰富的支持HTTP 协议的客户端编程工具包,并且它支持HTTP协议最新的版本。
HttpClient 被内置到Android SDK 中,因此可以在不添加任何额外jar 包情况下,直接使用。
1.3.1get 方式提交在1.2 节工程的基础上,只需要修改部分代码即可。
因此这里只给出核心代码。
【文件1-5】get方式提交数据代码片段1./**2.* HttpCLient使用get方式完成用户的登录3.*4.* @param view5.*/6.public void login3(View view){7.// 获取用户数据8.final String username= et_username.getText().toString().trim();119.final String password= et_password.getText().toString().trim();10.// 校验数据11.if (TextUtils.isEmpty(password) ||TextUtils.isEmpty(username)){12.Toast.makeText(this, "用户名或密码不能为空!",Toast.LENGTH_SHORT).show();13.return;14.}15.// 开启子线程16.new Thread(new Runnable(){17.18.@Override19.public void run() {20.String path=21."http://10.0.2.2:8080/userlogin/servlet/LoginServlet?username="22.+ URLEncoder.encode(username) +"&password=" +password;23.try{24. // 创建一个httpClient 对象25. HttpClient client = new DefaultHttpClient();26. // 创建一个请求方式27. HttpGet request = new HttpGet(path);28. // 执行操作29. HttpResponse response = client.execute(request);30. // 获取放回状态对象31. StatusLine statusLine = response.getStatusLine();32. // 获取状态码33. int statusCode =statusLine.getStatusCode();34. if (200 == statusCode) {35. // 获取服务器返回的对象36. HttpEntity entity = response.getEntity();37. // 获取输入流38. InputStream inputStream = entity.getContent();39. // 将输入流转化为字符串40. String data = StreamUtils.inputStream2String(inputStream);41. handler.obtainMessage(RESULT_OK, data).sendToTarget();42. } else {43. handler.obtainMessage(RESULT_CANCELED, statusCode).sendToTarget();44. }45.46.}catch (Exception e) {47. e.printStackTrace();48. handler.obtainMessage(RESULT_CANCELED, e).sendToTarget();50.}51.}).start();52.}。
IDEA中的HTTPClient使⽤教程介绍IDEA RESTful WebServices是⼀个类似jmeter,postman的⼯具。
可以使⽤纯⽂本编辑。
该⼯具是idea的⼀个组件,在Tools->Http client下;当然goland也是相同;低版本是Test Restful WebService,新版本的idea已经提⽰改功能废弃,建议使⽤new HTTP Client也就是我们此教程要介绍的⼯具;⽰例:创建demo1.http⽂件###点击右侧运⾏即可查看到结果HTTP请求中使⽤变量要在请求中提供变量,请将其括在双花括号中,如 {{variable}} 。
变量名称只能包含字母,数字,下划线符号 _ 或连字符 - 。
预定义的动态变量每次您运⾏请求时,动态变量都会⽣成⼀个值: $uuid :⽣成通⽤的唯⼀标识符(UUID-v4) $timestamp :⽣成当前的UNIX 时间戳 $randomInt :⽣成介于0到1000之间的随机整数。
GET http://localhost/api/get?id={{$uuid}}创建环境变量在项⽬内部,创建以下⽂件:在rest-client.env.json(或http-client.env.json)是包含常见的变量,其⽬的是要与你的项⽬⼀起分发的常规⽂件。
在rest-client.private.env.json(或http-client.private.env.json)是⼀个私⼈的⽂件可能包括密码,令牌,证书和其他敏感信息。
默认情况下,此⽂件被添加到VCS忽略⽂件列表中。
在httpclient.private.env.json⽂件中指定的变量的值将覆盖环境⽂件中的值。
{"dev": {"host": "http://127.0.0.1:80","name": "zhangsan"},"prod": {"host": "http://127.0.0.1:80","name":"lisi"}}调⽤⽰例GET http://{{host}}/api/get?name={{name}}脚本设置环境变量//设置环境变量> {%client.global.set("token", response.body.token);%}脚本检测可以对返回值进⾏打印,断⾔;# 登陆POST http://{{host}}/system/loginContent-Type: application/x-www-form-urlencodedusername=admin&password=123456> {%client.log(JSON.stringify(response.body));client.test("Request executed successfully", function() {client.assert(response.status === 200, "Response status is not 200");});client.test("Response content-type is json", function() {var type = response.contentType.mimeType;client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'");});client.test("Request code success", function() {client.assert(response.body.code === 0, "Response code is not 0");client.global.set("token", response.body.data);});%}###类型介绍clientclient.globalset(varName, varValue) // 设置全局变量get(varName) // 获取全局变量isEmpty // 检查 global 是否为空clear(varName) // 删除变量clearAll // 删除所有变量client.test(testName, func) // 创建⼀个名称为 testName 的测试client.assert(condition, message) // 校验条件 condition 是否成⽴,否则抛出异常 message client.log(text) // 打印⽇志responseresponse.body // 字符串或 JSON (如果 content-type 为 application/json .)response.headersvalueOf(headerName) // 返回第⼀个匹配 headerName 的值,如果没有匹配的返回 null valuesOf(headerName) // 返回所有匹配 headerName 的值的数组,如果没有匹配的返回空数组response.status // Http 状态码,如: 200 / 400response.contentTypemimeType // 返回 MIME 类型,如: text/plain , text/xml , application/json .charset // 返回编码 UTF-8 等⽰例test.http#### GET请求GET http://{{host}}/api/get?name={{name}}#### POST请求POST http://{{host}}/api/post/kvContent-Type: application/x-www-form-urlencodedname=zhangsan&age=11#### POST请求POST http://{{host}}/api/post/jsonContent-Type: application/jsonreferer: https:///cookie: name=zhangsan; age=11{"name":"zhangsan","age":11}###test2.http#### 未登录POST http://{{host}}/system/user/info> {%client.log(JSON.stringify(response.body));client.test("Request executed successfully", function() {client.assert(response.status === 404, "Response status is not 200");});client.test("Response content-type is json", function() {var type = response.contentType.mimeType;client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'"); });client.test("Request code fail", function() {client.assert(response.body.code === -1, "Response code is not -1");});%}#### 登陆POST http://{{host}}/system/loginContent-Type: application/x-www-form-urlencodedusername=admin&password=123456> {%client.log(JSON.stringify(response.body));client.test("Request executed successfully", function() {client.assert(response.status === 200, "Response status is not 200");});client.test("Response content-type is json", function() {var type = response.contentType.mimeType;client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'"); });client.test("Request code success", function() {client.assert(response.body.code === 0, "Response code is not 0");client.global.set("token", response.body.data);});%}#### 登陆后访问⽤户信息POST http://{{host}}/system/user/infotoken: {{token}}> {%client.log(JSON.stringify(response.body));client.test("Request executed successfully", function() {client.assert(response.status === 200, "Response status is not 200");});client.test("Response content-type is json", function() {var type = response.contentType.mimeType;client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'"); });client.test("Request code success", function() {client.assert(response.body.code === 0, "Response code is not 0");});%}#### 登陆后访问⽤户年龄POST http://{{host}}/system/user/agetoken: {{token}}> {%client.log(JSON.stringify(response.body));client.test("Request executed successfully", function() {client.assert(response.status === 200, "Response status is not 200");});client.test("Response content-type is json", function() {var type = response.contentType.mimeType;client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'");client.test("Request code success", function() {client.assert(response.body.code === 0, "Response code is not 0"); });%}###http-client.env.json{"dev": {"host": "http://127.0.0.1:80","name": "zhangsan"},"prod": {"host": "http://127.0.0.1:80","name":"lisi"}}main.gopackage mainimport ("/gogf/gf/frame/g""/gogf/gf/net/ghttp""/gogf/gf/util/guuid")var token stringfunc main() {s := g.Server()group := s.Group("/api")// 默认路径// GET带参数group.GET("/get", func(r *ghttp.Request) {r.Response.Writeln("Hello World!")r.Response.Writeln("name:", r.GetString("name"))})// POST KVgroup.POST("/post/kv", func(r *ghttp.Request) {r.Response.Writeln("func:test")r.Response.Writeln("name:", r.GetString("name"))r.Response.Writeln("age:", r.GetInt("age"))})// POST JSONgroup.POST("/post/json", func(r *ghttp.Request) {r.Response.Writeln("func:test2")r.Response.Writeln("name:", r.GetString("name"))r.Response.Writeln("age:", r.GetString("age"))h := r.Headerr.Response.Writeln("referer:", h.Get("referer"))r.Response.Writeln("cookie:", h.Get("cookie"))r.Response.Writeln(r.Cookie.Map())})// 模拟登陆system := s.Group("/system")// 登陆接⼝system.POST("/login", func(r *ghttp.Request) {if "admin" == r.GetString("username") &&"123456" == r.GetString("password") {token = guuid.New().String()r.Response.WriteJson(g.Map{"code": 0,"data": token,})r.Exit()}r.Response.WriteJson(g.Map{"code": -1,"data": "",})// 获取⽤户信息system.POST("/user/info", func(r *ghttp.Request) {if token != r.Header.Get("token") || token == "" {r.Response.WriteJson(g.Map{"code": -1,"data": "",})r.Exit()}// 返回⽤户信息r.Response.WriteJson(g.Map{"code": 0,"data": "zhangsan",})})// 获取⽤户年龄system.POST("/user/age", func(r *ghttp.Request) {if token != r.Header.Get("token") || token == "" {r.Response.WriteJson(g.Map{"code": -1,"data": "",})r.Exit()}// 返回⽤户信息r.Response.WriteJson(g.Map{"code": 0,"data": 11,})})s.SetPort(80)s.Run()}代码地址教程视频到此这篇关于IDEA中的HTTP Client使⽤教程的⽂章就介绍到这了,更多相关IDEA HTTP Client使⽤内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
ApacheHttpClient4使⽤教程基于HttpClient 4.5.21. 执⾏GET请求CloseableHttpClient httpClient = HttpClients.custom().build();CloseableHttpResponse response = httpClient.execute(new HttpGet("https://"));System.out.println(EntityUtils.toString(response.getEntity()));2. 执⾏POST请求1. 提交form表单参数CloseableHttpClient httpClient = HttpClients.custom().build();HttpPost httpPost = new HttpPost("https://");List<NameValuePair> formParams = new ArrayList<NameValuePair>();//表单参数formParams.add(new BasicNameValuePair("name1", "value1"));formParams.add(new BasicNameValuePair("name2", "value2"));UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "utf-8");httpPost.setEntity(entity);CloseableHttpResponse response = httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));2. 提交payload参数CloseableHttpClient httpClient = HttpClients.custom().build();HttpPost httpPost = new HttpPost("https://");StringEntity entity = new StringEntity("{\"id\": \"1\"}");httpPost.setEntity(entity);CloseableHttpResponse response = httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));3. post上传⽂件CloseableHttpClient httpClient = HttpClients.custom().build();HttpPost httpPost = new HttpPost("https://");MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();//要上传的⽂件multipartEntityBuilder.addBinaryBody("file", new File("temp.txt"));httpPost.setEntity(multipartEntityBuilder.build());CloseableHttpResponse response = httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));4. post提交multipart/form-data类型参数CloseableHttpClient httpClient = HttpClients.custom().build();HttpPost httpPost = new HttpPost("https://");MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();multipartEntityBuilder.addTextBody("username","wycm");multipartEntityBuilder.addTextBody("passowrd","123");//⽂件multipartEntityBuilder.addBinaryBody("file", new File("temp.txt"));httpPost.setEntity(multipartEntityBuilder.build());CloseableHttpResponse response = httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));3. 设置User-AgentCloseableHttpClient httpClient = HttpClients.custom().setUserAgent("Mozilla/5.0").build();CloseableHttpResponse response = httpClient.execute(new HttpGet("https://"));System.out.println(EntityUtils.toString(response.getEntity()));4. 设置重试处理器当请求超时, 会⾃动重试,最多3次HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {if (executionCount >= 3) {return false;}if (exception instanceof InterruptedIOException) {return true;}if (exception instanceof UnknownHostException) {return true;}if (exception instanceof ConnectTimeoutException) {return true;}if (exception instanceof SSLException) {return true;}HttpClientContext clientContext = HttpClientContext.adapt(context);HttpRequest request = clientContext.getRequest();boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);if (idempotent) {return true;}return false;};CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(retryHandler).build();httpClient.execute(new HttpGet("https://"));5. 重定向策略1. HttpClient默认情况会对302、307的GET和HEAD请求以及所有的303状态码做重定向处理2. 关闭⾃动重定向CloseableHttpClient httpClient = HttpClients.custom()//关闭httpclient重定向.disableRedirectHandling().build();3. POST⽀持302状态码重定向CloseableHttpClient httpClient = HttpClients.custom()//post 302⽀持重定向.setRedirectStrategy(new LaxRedirectStrategy()).build();CloseableHttpResponse response = httpClient.execute(new HttpPost("https://"));System.out.println(EntityUtils.toString(response.getEntity()));6. 定制cookie⽅式⼀:通过addHeader⽅式设置(不推荐这种⽅式)CloseableHttpClient httpClient = HttpClients.custom().build();HttpGet httpGet = new HttpGet("");httpGet.addHeader("Cookie", "name=value");httpClient.execute(httpGet);由于HttpClient默认会维护cookie状态。
(精华)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 ⼊门教程学习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的基本使用1. 引入HttpClient库:首先,需要将HttpClient库添加到项目的依赖中。
可以通过Maven或Gradle来添加依赖。
2. 创建HttpClient实例:接下来,需要创建一个HttpClient实例。
可以使用HttpClientBuilder类来构建实例。
````java```3. 创建Http请求:使用HttpGet、HttpPost等类来创建具体的Http请求对象。
可以设置请求的URL、请求头、请求体等信息。
````java```4. 执行Http请求:使用HttpClient实例来执行Http请求。
可以调用execute方法来发送请求,并获取响应对象。
````java```5. 处理Http响应:通过HttpResponse对象可以获取响应的状态码、响应头、响应体等信息。
````java```6. 释放资源:在完成所有的Http请求和响应处理后,需要释放相关的资源,如关闭HttpClient实例。
````java```除了基本的使用方法,HttpClient还提供了一些高级功能,例如:-设置请求超时时间:可以通过设置连接超时时间和读取超时时间来控制请求的超时行为。
````javaRequestConfig requestConfig = RequestConfig.custom.setConnectTimeout(5000) // 设置连接超时时间为5秒.setSocketTimeout(5000) // 设置读取超时时间为5秒.build(;```-设置请求头:可以通过设置请求头来发送特定的HTTP头部信息。
````java```- 发送POST请求:可以使用HttpPost类来发送POST请求,并设置请求体的内容。
````javaStringEntity requestEntity = new StringEntity("request body");```- Cookie管理:HttpClient可以自动处理和管理Cookie,可以通过CookieStore接口来获取和设置Cookie。
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 = new DefaultHttpClient();HttpGet httpget = new HttpGet("http://localhost/");HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();if (entity != null) {InputStream instream = entity.getContent();int l;byte[] tmp = new byte[2048];while ((l = instream.read(tmp)) != -1) {}1.1.1 HTTP请求所有HTTP请求有一个组合了方法名,请求URI和HTTP协议版本的请求行。
HttpClient支持所有定义在HTTP/1.1版本中的HTTP方法:GET,HEAD,POST,PUT,DELETE,TRACE和OPTIONS。
对于每个方法类型都有一个特殊的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions。
请求的URI是统一资源定位符,它标识了应用于哪个请求之上的资源。
HTTP请求URI 包含一个协议模式,主机名称,可选的端口,资源路径,可选的查询和可选的片段。
HttpGet httpget = new HttpGet("/search?hl=en&q=httpclient&btnG=Google+Search&aq= f&oq=");HttpClient提供很多工具方法来简化创建和修改执行URI。
URI也可以编程来拼装:URI uri = URIUtils.createURI("http", "", -1, "/search","q=httpclient&btnG=Google+Search&aq=f&oq=", null);HttpGet httpget = new HttpGet(uri);System.out.println(httpget.getURI());输出内容为:/search?q=httpclient&btnG=Google+Search&aq=f&oq= 查询字符串也可以从独立的参数中来生成:List<NameValuePair> qparams = new ArrayList<NameValuePair>();qparams.add(new BasicNameValuePair("q", "httpclient"));qparams.add(new BasicNameValuePair("btnG", "Google Search"));qparams.add(new BasicNameValuePair("aq", "f"));qparams.add(new BasicNameValuePair("oq", null));URI uri = URIUtils.createURI("http", "", -1, "/search",URLEncodedUtils.format(qparams, "UTF-8"), null);HttpGet httpget = new HttpGet(uri);System.out.println(httpget.getURI());输出内容为:/search?q=httpclient&btnG=Google+Search&aq=f&oq= 1.1.2 HTTP响应HTTP响应是由服务器在接收和解释请求报文之后返回发送给客户端的报文。
响应报文的第一行包含了协议版本,之后是数字状态码和相关联的文本段。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, "OK");System.out.println(response.getProtocolVersion());System.out.println(response.getStatusLine().getStatusCode());System.out.println(response.getStatusLine().getReasonPhrase());System.out.println(response.getStatusLine().toString());输出内容为:HTTP/1.1200HTTP/1.1 200 OK1.1.3 处理报文头部一个HTTP报文可以包含很多描述如内容长度,内容类型等信息属性的头部信息。
HttpClient提供获取,添加,移除和枚举头部信息的方法。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, "OK");response.addHeader("Set-Cookie","c1=a; path=/; domain=localhost");response.addHeader("Set-Cookie","c2=b; path=\"/\", c3=c; domain=\"localhost\"");Header h1 = response.getFirstHeader("Set-Cookie");System.out.println(h1);Header h2 = response.getLastHeader("Set-Cookie");System.out.println(h2);Header[] hs = response.getHeaders("Set-Cookie");System.out.println(hs.length);输出内容为:Set-Cookie: c1=a; path=/; domain=localhostSet-Cookie: c2=b; path="/", c3=c; domain="localhost"获得给定类型的所有头部信息最有效的方式是使用HeaderIterator接口。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, "OK");response.addHeader("Set-Cookie","c1=a; path=/; domain=localhost");response.addHeader("Set-Cookie","c2=b; path=\"/\", c3=c; domain=\"localhost\"");HeaderIterator it = response.headerIterator("Set-Cookie");while (it.hasNext()) {System.out.println(it.next());}输出内容为:Set-Cookie: c1=a; path=/; domain=localhostSet-Cookie: c2=b; path="/", c3=c; domain="localhost"它也提供解析HTTP报文到独立头部信息元素的方法方法。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, "OK");response.addHeader("Set-Cookie","c1=a; path=/; domain=localhost");response.addHeader("Set-Cookie","c2=b; path=\"/\", c3=c; domain=\"localhost\"");HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Set-Cookie"));while (it.hasNext()) {HeaderElement elem = it.nextElement();System.out.println(elem.getName() + " = " + elem.getValue());NameValuePair[] params = elem.getParameters();for (int i = 0; i < params.length; i++) {System.out.println(" " + params[i]);}}输出内容为:c1 = apath=/domain=localhostc2 = bpath=/c3 = cdomain=localhost1.1.4 HTTP实体HTTP报文可以携带和请求或响应相关的内容实体。