千家信息网

HttpClient的使用实例

发表于:2024-09-27 作者:千家信息网编辑
千家信息网最后更新 2024年09月27日,本篇内容主要讲解"HttpClient的使用实例",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"HttpClient的使用实例"吧!HttpClient的使
千家信息网最后更新 2024年09月27日HttpClient的使用实例

本篇内容主要讲解"HttpClient的使用实例",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"HttpClient的使用实例"吧!

HttpClient的使用:

1)httpClient的简单使用:

import java.net.URI;import java.util.ArrayList;import java.util.List;import org.apache.http.NameValuePair;import org.apache.http.client.config.RequestConfig;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.client.utils.URIBuilder;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;public class HttpClientDemo {        public static void main(String[] args) throws Exception {                // 1.创建Httpclient对象                CloseableHttpClient httpclient = HttpClients.createDefault();                // 2.1创建http GET请求,并设置参数                String url = "http://www.jxn.com/";                URI uri = new URIBuilder(url).setParameter("name", "jack").setParameter("age", "1").build();                HttpGet httpGet = new HttpGet(uri);                // 2.2创建http POST请求,并设置参数                HttpPost httpPost = new HttpPost(url);                List parameters = new ArrayList();                parameters.add(new BasicNameValuePair("name", "jack"));                parameters.add(new BasicNameValuePair("age", "1"));                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);                httpPost.setEntity(formEntity);                                                // 3.构建请求配置信息                RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间                                .setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间                                .setSocketTimeout(10 * 1000) // 数据传输的最长时间                                .setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用                                .build();                httpGet.setConfig(config);                httpPost.setConfig(config);                CloseableHttpResponse response = null;                try {                        // 4.执行请求                        response = httpclient.execute(httpGet);//            response = httpclient.execute(httpPost);                                                                        if (response.getStatusLine().getStatusCode() == 200) { // 判断返回状态是否为200                                String content = EntityUtils.toString(response.getEntity(), "UTF-8");                                System.out.println(content);                        }                       } finally {                        if (response != null) {                                response.close();                        }                        httpclient.close();                }        }}

2)使用httpClient连接池:

import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.HttpClientConnectionManager;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.util.EntityUtils;public class HttpClientConnectionManagerDemo {        public static void main(String[] args) throws Exception {                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();                connectionManager.setMaxTotal(200);                        // 设置最大连接数                connectionManager.setDefaultMaxPerRoute(20);       // 设置每个主机地址的并发数                // 执行一次get请求                doGet(connectionManager);        }        public static void doGet(HttpClientConnectionManager connectionManager) throws Exception {                CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();                String url = "http://www.jxn.com/";                HttpGet httpGet = new HttpGet(url);                CloseableHttpResponse response = null;                try {                        response = httpClient.execute(httpGet);                        if (response.getStatusLine().getStatusCode() == 200) {                                String content = EntityUtils.toString(response.getEntity(), "UTF-8");                                System.out.println(content);                        }                } finally {                        if (response != null) {                                response.close();                        }                        // 此处不能关闭httpClient!如果把httpClient关闭掉,则连接池也会被销毁                        // httpClient.close();                }        }}

3)HttpClient与Spring整合:

【1】pom.xml文件:

        org.apache.httpcomponents        httpclient        4.3.5

【2】spirng配置文件applicationContext-httpclient.xml:

                                                                                                属性配置文件httpclient.properties:        http.maxTotal=200        http.defaultMaxPerRoute=50        http.connectTimeout=1000        http.connectionRequestTimeout=500        http.socketTimeout=10000        http.staleConnectionCheckEnabled=true

【3】封装成Service:

import java.io.IOException;import java.net.URISyntaxException;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;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.client.utils.URIBuilder;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.springframework.beans.BeansException;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.BeanFactoryAware;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.jxn.common.httpclient.HttpResult;[@Service](https://my.oschina.net/service)public class ApiService implements BeanFactoryAware {        private BeanFactory beanFactory;        @Autowired(required = false)        private RequestConfig requestConfig;                        [@Override](https://my.oschina.net/u/1162528)        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {                this.beanFactory = beanFactory;        }        private CloseableHttpClient getHttpClient() {                return this.beanFactory.getBean(CloseableHttpClient.class);        }                // 执行GET请求        public String doGet(String url) throws ClientProtocolException, IOException {                HttpGet httpGet = new HttpGet(url);                httpGet.setConfig(requestConfig);                CloseableHttpResponse response = null;                try {                        // 执行请求                        response = getHttpClient().execute(httpGet);                        // 判断返回状态是否为200                        if (response.getStatusLine().getStatusCode() == 200) {                                return EntityUtils.toString(response.getEntity(), "UTF-8");                        }                } finally {                        if (response != null) {                                response.close();                        }                }                return null;        }        // 带有参数的GET请求        public String doGet(String url, Map params) throws ClientProtocolException, IOException,                        URISyntaxException {                URIBuilder builder = new URIBuilder(url);                for (Map.Entry entry : params.entrySet()) {                        builder.setParameter(entry.getKey(), entry.getValue());                }                return doGet(builder.build().toString());        }        // 执行post请求        public HttpResult doPost(String url, Map params) throws IOException {                // 创建http POST请求                HttpPost httpPost = new HttpPost(url);                httpPost.setConfig(requestConfig);                if (null != params) {                        List parameters = new ArrayList(0);                        for (Map.Entry entry : params.entrySet()) {                                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));                        }                        // 构造一个form表单式的实体                        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");                        httpPost.setEntity(formEntity);                }                CloseableHttpResponse response = null;                try {                        response = getHttpClient().execute(httpPost);                        return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(                                        response.getEntity(), "UTF-8"));                } finally {                        if (response != null) {                                response.close();                        }                }        }        // 执行post请求,发送json数据        public HttpResult doPostJson(String url, String json) throws IOException {                // 创建http POST请求                HttpPost httpPost = new HttpPost(url);                httpPost.setConfig(requestConfig);                if (null != json) {                        // 构造一个字符串的实体                        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);                        httpPost.setEntity(stringEntity);                }                CloseableHttpResponse response = null;                try {                        response = getHttpClient().execute(httpPost);                        return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(                                        response.getEntity(), "UTF-8"));                } finally {                        if (response != null) {                                response.close();                        }                }        }}// 返回的结果public class HttpResult {        private Integer code;        private String data;        public HttpResult() {        }        public HttpResult(Integer code, String data) {                this.code = code;                this.data = data;        }        public Integer getCode() {                return code;        }        public void setCode(Integer code) {                this.code = code;        }        public String getData() {                return data;        }        public void setData(String data) {                this.data = data;        }}

【4】实现定期关闭无效的连接:

import org.apache.http.conn.HttpClientConnectionManager;public class IdleConnectionEvictor extends Thread {        private final HttpClientConnectionManager connectionManager;        private volatile boolean shutdown;        // 创建IdleConnectionEvictor对象的时候,启动线程        public IdleConnectionEvictor(HttpClientConnectionManager connectionManager) {                this.connectionManager = connectionManager;                this.start();        }        [@Override](https://my.oschina.net/u/1162528)        public void run() {                try {                        while (!shutdown) {                                synchronized (this) {                                        wait(5000);                                        // 关闭失效的连接(每隔5秒检查一次)                                        connectionManager.closeExpiredConnections();                                }                        }                } catch (InterruptedException ex) {                        // 结束                }        }        public void shutdown() {                shutdown = true;                synchronized (this) {                        notifyAll();                }        }}

到此,相信大家对"HttpClient的使用实例"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

UTF-8 实例 最长 参数 文件 时间 配置 内容 实体 对象 数据 状态 学习 实用 更深 最大 主机 信息 兴趣 地址 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 企业数据库的优势 魔兽世界怀旧服装备价格数据库 阿里云服务器连接失败 楚雄州公安网络安全保卫支队 滴滴的一键服务器 电脑地址管理编辑服务器信息 网络安全专项行动的通知 网络安全卡通宣传画 三级网络技术怎么自学 云数据库面临的安全问题 科技互联网行业人士安家 2021网络安全网上答题 陕西泥人互联网科技有限公司 第五空间网络安全大赛答案 甘肃智慧人口gis系统软件开发 重庆合川高新技术网络安全产业城 网络安全女总裁 软件开发改进 办公软件开发需要哪些技术 网吧无盘服务器的长宽高 进销存管理软件开发技术 电脑连接数据库服务器 qt开发访问数据库 网络安全科普讲解 简要描述什么是网络安全 选修三网络技术应用题答案 网络安全法的责任主体是 什么情况下数据库会断开 软件开发商该不该收取维护费 搭建服务器算前端还是后端
0