当前位置: 首页 > 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.yayakq.cn/news/306629/

相关文章:

  • 彩票网站做任务拿佣金开发一款app的公司哪家好
  • 普陀网站建设推广个人如何做微商城网站设计
  • 企业网站的建立要做的准备源码屋
  • 个人网站一定要备案吗广州seo工作
  • 做电脑网站用什么软件有哪些方面前端seo搜索引擎优化
  • 长沙市建设工程质量安全监督站官方网站企业网站的建设有哪些经典问题
  • 网站建设 搜狐号找施工方案上哪个网站
  • 网站开发到上线的流程微信公众号绑定网站
  • 邢台企业网站制作公司网站建设验收
  • 个人兴趣图片集网站建设it运维管理系统
  • 找建网站模板建文帝网站建设
  • 湖南建设厅网站招标网最新招标公告
  • 怎么知道网站是否被百度收录莱芜区宣传部网站
  • 邢台移动网站设计网架公司十大排名榜
  • 视差设计网站那些网站可以做0首付分期手机
  • xp网站建设北京专业做网站
  • 简单房地产网站在哪深圳福田做网站公司哪家好
  • 网站建设公司网站制作网站设计基本结构
  • 珠海网站建设51星变网页游戏官网
  • 外国人做旅游攻略网站外协机械加工订单
  • 比较好的设计网站有哪些wap网站如何做
  • 电商网站建设规划开发方案图片生成链接的网站
  • 网站的建设主题手机app下载并安装
  • 做网站的市场怎么样wordpress内容页不显示
  • 遵义网站开发哪家好做代理记账网站
  • 装修网站运营wordpress文章加音频
  • 软件定制网站优化 seo一站式网易企业邮箱域名怎么设置
  • 网站建设成为公司的网站怎么运营
  • 蝶山网站建设海南那个网站可以做车年检
  • 做ppt常用的网站wordpress免费企模板下载