HttpClient使用详解

1. 什么是httpclient

        HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
       下载地址:http://hc.apache.org/

2. 功能介绍

       以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。

         (1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)

         (2)支持自动转向

         (3)支持 HTTPS 协议

         (4)支持代理服务器等

3. 导入依赖

       

4.1. 执行GET请求

public class DoGET {public static void main(String[] args) throws Exception {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http GET请求HttpGet httpGet = new HttpGet("http://www.baidu.com/");CloseableHttpResponse response = null;try {// 执行请求response = httpclient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {String content = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println("内容长度:" + content.length());
//                FileUtils.writeStringToFile(new File("C:\\baidu.html"), content);}} finally {if (response != null) {response.close();}httpclient.close();}}
}

4.2. 执行带参数GET请求

public class DoGETParam {public static void main(String[] args) throws Exception {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();// 定义请求的参数URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();System.out.println(uri);// 创建http GET请求HttpGet httpGet = new HttpGet(uri);CloseableHttpResponse response = null;try {// 执行请求response = httpclient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {String content = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println(content);}} finally {if (response != null) {response.close();}httpclient.close();}}
}

5.1. 执行post请求

public class DoPOST {public static void main(String[] args) throws Exception {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http POST请求HttpPost httpPost = new HttpPost("http://www.oschina.net/");CloseableHttpResponse response = null;try {// 执行请求response = httpclient.execute(httpPost);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {String content = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println(content);}} finally {if (response != null) {response.close();}httpclient.close();}}
}

5.2. 执行带参数post请求

public class DoPOSTParam {public static void main(String[] args) throws Exception {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http POST请求HttpPost httpPost = new HttpPost("http://www.oschina.net/search");// 设置2个post参数,一个是scope、一个是qList<NameValuePair> parameters = new ArrayList<NameValuePair>(0);parameters.add(new BasicNameValuePair("scope", "project"));parameters.add(new BasicNameValuePair("q", "java"));// 构造一个form表单式的实体UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);// 将请求实体设置到httpPost对象中httpPost.setEntity(formEntity);CloseableHttpResponse response = null;try {// 执行请求response = httpclient.execute(httpPost);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {String content = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println(content);}} finally {if (response != null) {response.close();}httpclient.close();}}
}

6. 一个封装HttpClient通用工具类

public class HttpClientUtil {public static String doGet(String url, Map<String, String> param) {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();String resultString = "";CloseableHttpResponse response = null;try {// 创建uriURIBuilder builder = new URIBuilder(url);if (param != null) {for (String key : param.keySet()) {builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 创建http GET请求HttpGet httpGet = new HttpGet(uri);// 执行请求response = httpclient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {resultString = EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {e.printStackTrace();} finally {try {if (response != null) {response.close();}httpclient.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}public static String doGet(String url) {return doGet(url, null);}public static String doPost(String url, Map<String, String> param) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建参数列表if (param != null) {List<NameValuePair> paramList = new ArrayList<>();for (String key : param.keySet()) {paramList.add(new BasicNameValuePair(key, param.get(key)));}// 模拟表单UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);httpPost.setEntity(entity);}// 执行http请求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "utf-8");} catch (Exception e) {e.printStackTrace();} finally {try {response.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return resultString;}public static String doPost(String url) {return doPost(url, null);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/443326.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Nginx反向代理及负载均衡

1. nginx反向代理 1.1. 什么是反向代理 通常的代理服务器&#xff0c;只用于代理内部网络对Internet的连接请求&#xff0c;客户机必须指定代理服务器,并将本来要直接发送到Web服务器上的http请求发送到代理服务器中由代理服务器向Internet上的web服务器发起请求&#xff0c;…

SolrCloud详解及搭建

1. 什么是SolrCloud 1.1. 什么是SolrCloud SolrCloud(solr 云)是Solr提供的分布式搜索方案&#xff0c;当你需要大规模&#xff0c;容错&#xff0c;分布式索引和检索能力时使用SolrCloud。当一个系统的索引数据量少的时候是不需要使用SolrCloud的&#xff0c;当索引量很大&am…

Intellij IDEA 快捷键整理

【常规】CtrlShift Enter&#xff0c;语句完成“&#xff01;”&#xff0c;否定完成&#xff0c;输入表达式时按 “&#xff01;”键CtrlE&#xff0c;最近的文件CtrlShiftE&#xff0c;最近更改的文件ShiftClick&#xff0c;可以关闭文件Ctrl[ OR ]&#xff0c;可以跑到大括…

谈谈Java开发中的对象拷贝

在Java开发工作中&#xff0c;有很多时候我们需要将不同的两个对象实例进行属性复制&#xff0c;从而基于源对象的属性信息进行后续操作&#xff0c;而不改变源对象的属性信息。这两个对象实例有可能是同一个类的两个实例&#xff0c;也可能是不同类的两个实例&#xff0c;但是…

gitmaven命令

git命令 git diff #查看差异 git push origin feature/recover_pwd_bug #推送 git commit -m ‘perf #重置密码逻辑优化 git log #查看提交版本号 git reset --hard <版本号> #本地回退到相应的版本 git push origin <分支名> --force #远端的仓库也回退到相应…

【算法系列之一】二叉树最小深度

题目&#xff1a; 给定一个二叉树&#xff0c;找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3/ \9 20/ \15 7 返回它的最小深度 2. 答案&#xf…

【算法系列之二】反波兰式

问题&#xff1a; 用反波兰式表示算术表达式的值。 有效运算符是,-,*,/。每个操作数可以是一个整数或另一个表达式。 一些例子&#xff1a; ["2", "1", "", "3", "*"] -> ((2 1) * 3) -> 9["4", "13…

【算法系列之三】单链表反转

问题&#xff1a; 实现单链表反转 答案&#xff1a; 链表准备 class Node {private int Data;// 数据域private Node Next;// 指针域public Node(int Data) {// super();this.Data Data;}public int getData() {return Data;}public void setData(int Data) {this.Data D…

Java常见异常总结

1、java.lang.NullPointerException(空指针异常)   调用了未经初始化的对象或者是不存在的对象 经常出现在创建图片&#xff0c;调用数组这些操作中&#xff0c;比如图片未经初始化&#xff0c;或者图片创建时的路径错误等等。对数组操作中出现空指针&#xff0c; 即把数组的…

从数据库表中随机获取N条记录的SQL语句

Oracle: select * from (select * from tableName order by dbms_random.value) where rownum < N; MS SQLServer: select top N * from tableName order by newid(); My SQL: select * from tableName order by rand() limit N; 转自&#xff1a;http://blog.csdn.net/sent…

Linux下的MySQL安装及卸载

1.1 查看mysql的安装路径&#xff1a; [rootbogon ~]# whereis mysql mysql: /usr/bin/mysql /usr/lib/mysql/usr/share/mysql /usr/share/man/man1/mysql.1.gz 1.2 查看mysql的安装包&#xff1a; [rootbogon ~]# rpm -qa|grep mysql mysql-community-client-5.6.26-2.…

mysql explain用法

explain显示了mysql如何使用索引来处理select语句以及连接表。可以帮助选择更好的索引和写出更优化的查询语句。使用方法&#xff0c;在select语句前加上explain就可以了&#xff0c;如&#xff1a;explain select * from statuses_status where id11;创建测试表&#xff1a;CR…

Linux 性能检查命令总结

如果你的Linux服务器突然负载暴增&#xff0c;告警短信快发爆你的手机&#xff0c;如何在最短时间内找出Linux性能问题所在&#xff1f;

线程池的各种使用场景

&#xff08;1&#xff09;高并发、任务执行时间短的业务&#xff0c;线程池线程数可以设置为CPU核数1&#xff0c;减少线程上下文的切换 &#xff08;2&#xff09;并发不高、任务执行时间长的业务要区分开看&#xff1a; a&#xff09;假如是业务时间长集中在IO操作上…

Java线程面试题 Top 50

不管你是新程序员还是老手&#xff0c;你一定在面试中遇到过有关线程的问题。Java语言一个重要的特点就是内置了对并发的支持&#xff0c;让Java大受企业和程序员的欢迎。大多数待遇丰厚的Java开发职位都要求开发者精通多线程技术并且有丰富的Java程序开发、调试、优化经验&…

深入理解Semaphore

使用 Semaphore是计数信号量。Semaphore管理一系列许可证。每个acquire方法阻塞&#xff0c;直到有一个许可证可以获得然后拿走一个许可证&#xff1b;每个release方法增加一个许可证&#xff0c;这可能会释放一个阻塞的acquire方法。然而&#xff0c;其实并没有实际的许可证这…

【算法系列之四】柱状图储水

题目&#xff1a; 给定一个数组&#xff0c;每个位置的值代表一个高度&#xff0c;那么整个数组可以看做是一个直方图&#xff0c; 如果把这个直方图当作容器的话&#xff0c;求这个容器能装多少水 例如&#xff1a;3&#xff0c;1&#xff0c;2&#xff0c;4 代表第一个位…

盐城大数据产业园人才公寓_岳西大数据产业园规划设计暨建筑设计方案公布,抢先一睹效果图...

近日&#xff0c;岳西县大数据产业园规划设计暨建筑设计方案公布。岳西县大数据产业园项目总占地面积17014.10㎡(约合25.52亩)&#xff0c;拟建总建筑面积约为61590.84㎡(地上建筑面积39907.49㎡&#xff0c;地下建筑面积21602.35㎡)。以“科技圆环”为主题&#xff0c;组建出一…

【算法系列之五】对称二叉树

给定一个二叉树&#xff0c;检查它是否是镜像对称的。 例如&#xff0c;二叉树 [1,2,2,3,4,4,3] 是对称的。 1/ \2 2/ \ / \ 3 4 4 3但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1/ \2 2\ \3 3 说明: 如果你可以运用递归和迭代两种方法解决这个问题&a…

【算法系列之六】两整数之和

不使用运算符 和 - &#xff0c;计算两整数 a 、b 之和。 示例 1: 输入: a 1, b 2 输出: 3示例 2: 输入: a -2, b 3 输出: 1 方法一&#xff1a;递归 public static int getSum1(int a, int b) {if ((a & b) ! 0) { // 判断是否有进位return getSum1(a ^ b, (a &…