当前位置: 首页 > news >正文

最好网站制作工具百度联盟怎么加入

最好网站制作工具,百度联盟怎么加入,网站里的横幅怎么做,房管局官网本文向您展示如何使用Apache HttpClient发送HTTP GET / POST请求&#xff0c;JSON&#xff0c;身份验证&#xff0c;超时&#xff0c;重定向以及一些常用示例。 PS已通过HttpClient 4.5.10测试 pom.xml <dependency><groupId>org.apache.httpcomponents</grou…
HttpClient徽标

本文向您展示如何使用Apache HttpClient发送HTTP GET / POST请求,JSON,身份验证,超时,重定向以及一些常用示例。

PS已通过HttpClient 4.5.10测试

pom.xml
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.10</version></dependency>

1.发送GET请求

1.1手动关闭。

HttpClientExample1_1.java
package com.mkyong.http;import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientExample1_1 {public static void main(String[] args) throws IOException {CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet request = new HttpGet("https://httpbin.org/get");// add request headersrequest.addHeader("custom-key", "mkyong");request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");CloseableHttpResponse response = httpClient.execute(request);try {// Get HttpResponse StatusSystem.out.println(response.getProtocolVersion());              // HTTP/1.1System.out.println(response.getStatusLine().getStatusCode());   // 200System.out.println(response.getStatusLine().getReasonPhrase()); // OKSystem.out.println(response.getStatusLine().toString());        // HTTP/1.1 200 OKHttpEntity entity = response.getEntity();if (entity != null) {// return it as a StringString result = EntityUtils.toString(entity);System.out.println(result);}} finally {response.close();}} finally {httpClient.close();}}}

1.2使用try-with-resources结束。

HttpClientExample1_2.java
package com.mkyong.http;import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientExample1_2 {public static void main(String[] args) throws IOException {HttpGet request = new HttpGet("https://httpbin.org/get");// add request headersrequest.addHeader("custom-key", "mkyong");request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(request)) {// Get HttpResponse StatusSystem.out.println(response.getProtocolVersion());              // HTTP/1.1System.out.println(response.getStatusLine().getStatusCode());   // 200System.out.println(response.getStatusLine().getReasonPhrase()); // OKSystem.out.println(response.getStatusLine().toString());        // HTTP/1.1 200 OKHttpEntity entity = response.getEntity();if (entity != null) {// return it as a StringString result = EntityUtils.toString(entity);System.out.println(result);}}}}

2.发送普通的POST请求

HttpClientExample2_1.java
package com.mkyong.http;import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;public class HttpClientExample2_1 {public static void main(String[] args) {try {String result = sendPOST("https://httpbin.org/post");System.out.println(result);} catch (IOException e) {e.printStackTrace();}}private static String sendPOST(String url) throws IOException {String result = "";HttpPost post = new HttpPost(url);// add request parameters or form parametersList<NameValuePair> urlParameters = new ArrayList<>();urlParameters.add(new BasicNameValuePair("username", "abc"));urlParameters.add(new BasicNameValuePair("password", "123"));urlParameters.add(new BasicNameValuePair("custom", "secret"));post.setEntity(new UrlEncodedFormEntity(urlParameters));try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(post)){result = EntityUtils.toString(response.getEntity());}return result;}}

3.发送JSON POST请求

3.1使用JSON格式的数据发送POST请求。 密钥将JSON格式的日期传递到StringEntity

HttpClientExample3_1.java
package com.mkyong.http;import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientExample3_1 {public static void main(String[] args) {try {String result = sendPOST("https://httpbin.org/post");System.out.println(result);} catch (IOException e) {e.printStackTrace();}}private static String sendPOST(String url) throws IOException {String result = "";HttpPost post = new HttpPost(url);StringBuilder json = new StringBuilder();json.append("{");json.append("\"name\":\"mkyong\",");json.append("\"notes\":\"hello\"");json.append("}");// send a JSON datapost.setEntity(new StringEntity(json.toString()));try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(post)) {result = EntityUtils.toString(response.getEntity());}return result;}}

3.2向Cloudflare API发送POST请求以阻止IP地址。 标头中的身份验证。

HttpClientExample3_2.java
package com.mkyong.http;import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientExample3_2 {public static void main(String[] args) {try {String result = blockIP("1.1.1.1");System.out.println(result);} catch (IOException e) {e.printStackTrace();}}private static String blockIP(String ip) throws IOException {String result = "";HttpPost post = new HttpPost("https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules");post.addHeader("content-type", "application/json");post.addHeader("X-Auth-Email", "email");post.addHeader("X-Auth-Key", "token123");String block = "{\"target\":\"ip\",\"value\":\"" + ip + "\"}";StringBuilder entity = new StringBuilder();entity.append("{");entity.append("\"mode\":\"block\",");entity.append("\"configuration\":" + block + ",");entity.append("\"notes\":\"hello\"");entity.append("}");// send a JSON datapost.setEntity(new StringEntity(entity.toString()));try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(post)) {result = EntityUtils.toString(response.getEntity());}return result;}}

4. HTTP基本认证

HttpClientExample4_1.java
package com.mkyong.http;import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientExample4_1 {public static void main(String[] args) throws IOException {HttpGet request = new HttpGet("http://localhost:8080/books");CredentialsProvider provider = new BasicCredentialsProvider();provider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("user", "password"));try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();CloseableHttpResponse response = httpClient.execute(request)) {// 401 if wrong user/passwordSystem.out.println(response.getStatusLine().getStatusCode());   HttpEntity entity = response.getEntity();if (entity != null) {// return it as a StringString result = EntityUtils.toString(entity);System.out.println(result);}}}}

阅读本文– Apache HttpClient基本身份验证示例

5.常见问题

5.1禁用重定向。

HttpClientExample5_1.java
package com.mkyong.customer;import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HttpClientExample5_1 {public static void main(String[] args) throws IOException {HttpGet request = new HttpGet("https://t.co/calv72DH8f");request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();CloseableHttpResponse response = httpClient.execute(request)) {// Get HttpResponse StatusSystem.out.println(response.getProtocolVersion());              // HTTP/1.1System.out.println(response.getStatusLine().getStatusCode());   // 301System.out.println(response.getStatusLine().getReasonPhrase()); // Moved PermanentlySystem.out.println(response.getStatusLine().toString());        // HTTP/1.1 301 Moved PermanentlyHttpEntity entity = response.getEntity();if (entity != null) {// return it as a StringString result = EntityUtils.toString(entity);System.out.println(result);}}}}

5.2连接超时在请求级别。

HttpGet request = new HttpGet("https://httpbin.org/get");// 5 seconds timeoutRequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).build();request.setConfig(requestConfig);try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(request)) {//...}

5.3连接超时在客户端级别。

HttpGet request = new HttpGet("https://httpbin.org/get");// 5 seconds timeoutRequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).build();//request.setConfig(requestConfig);try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();CloseableHttpResponse response = httpClient.execute(request)) {//...}

5.4配置代理服务器。 阅读HttpClient代理配置

HttpGet request = new HttpGet("https://httpbin.org/get");RequestConfig requestConfig = RequestConfig.custom().setProxy(new HttpHost("company.proxy.url", 8080)).build();request.setConfig(requestConfig);try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(request)) {//...}

5.5打开cookie。 读取HTTP Cookie

HttpGet request = new HttpGet("https://httpbin.org/get");RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();request.setConfig(requestConfig);try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(request)) {//...}

5.6获取响应头以及媒体类型。

try (CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = httpClient.execute(request)) {HttpEntity entity = response.getEntity();Header headers = entity.getContentType();System.out.println(headers);//...}

样品

Content-Type: application/json
{"args": {}, "headers": {"Accept-Encoding": "gzip,deflate", "Custom-Key": "mkyong", "Host": "httpbin.org", "User-Agent": "Googlebot"}, "origin": "202.168.71.227, 202.168.71.227", "url": "https://httpbin.org/get"
}

参考文献

  • Apache HttpClient
  • HttpClient教程
  • Apache HttpClient基本身份验证示例

翻译自: https://mkyong.com/java/apache-httpclient-examples/

http://www.khdw.cn/news/20004.html

相关文章:

  • 做网站会员金字塔系统申请网址怎么申请的
  • 政府部门网站建设需求百度关键词多少钱一个月
  • 重庆网站建设网络推广新媒体运营是做什么
  • 昆明网站建设哪家比较好海外aso优化
  • 图片在线设计网站最吸引人的营销广告词
  • 中企网络科技建站防疫优化措施
  • 三原做网站北京营销推广网站建设
  • 网站建设力度怎么在百度推广自己的网站
  • 做网站中心软文推广
  • 有没有可以做各种字体的网站巨量数据官网
  • 企业信用信息查询公示系统陕西seo优化啥意思
  • 网站重新安装室内设计培训
  • 手机图片制作软件免费seo排名赚app最新版本
  • 安吉网站设计百度在线扫题入口
  • 站长统计在线观看博客seo优化技术
  • 那个网站可以做空比特币现在有哪些培训学校
  • 天津网站建设咨询有哪些推广平台和渠道
  • 南京外贸网站建设案例企业推广视频
  • 网站正在建设中AV 手机版医院营销策略的具体方法
  • 沈阳网站关键词优化编写网页的软件
  • 旅游网站模板免费下载seo优化排名工具
  • 泰安网站建设公司最佳搜索引擎
  • 广州专业做网站多少钱品牌推广方案思维导图
  • 免费制作个人网站站长工具外链查询
  • 佛山做推广网站的企业营销策划书如何编写
  • 网站接口怎么做推广网站平台
  • 河北建设网工程信息网网站seo规划
  • 安卓应用开发环境seo关键词优化推广
  • 优化网站内容的方法爱站权重
  • 自己网站如何做关键词排名靠前广告营销策划