前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Java中使用HttpClient调用api

Java中使用HttpClient调用api

作者头像
Vincent-yuan
发布于 2021-06-11 10:41:40
发布于 2021-06-11 10:41:40
3K00
代码可运行
举报
文章被收录于专栏:Vincent-yuanVincent-yuan
运行总次数:0
代码可运行

java中可以使用3种方式调用api

  • HttpURLConnection
  • HttpClient
  • RestTemplate

这里要讲的是HttpClient的方式。

一.简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

二.特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲到socket服务器

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取

三.使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接

四.实例

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.test;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
 
import javax.net.ssl.SSLContext;
 
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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 org.junit.Test;
 
public class HttpClientTest {
 
    @Test
    public void jUnitTest() {
        get();
    }
 
    /**
     * HttpClient连接SSL
     */
    public void ssl() {
        CloseableHttpClient httpclient = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
            try {
                // 加载keyStore d:\\tomcat.keystore  
                trustStore.load(instream, "123456".toCharArray());
            } catch (CertificateException e) {
                e.printStackTrace();
            } finally {
                try {
                    instream.close();
                } catch (Exception ignore) {
                }
            }
            // 相信自己的CA和所有自签名的证书
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            // 只允许使用TLSv1协议
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            // 创建http请求(get方式)
            HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
            System.out.println("executing request" + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    System.out.println(EntityUtils.toString(entity));
                    EntityUtils.consume(entity);
                }
            } finally {
                response.close();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     * post方式提交表单(模拟用户登录请求)
     */
    public void postForm() {
        // 创建默认的httpClient实例.  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost  
        HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
        // 创建参数队列  
        List formparams = new ArrayList();
        formparams.add(new BasicNameValuePair("username", "admin"));
        formparams.add(new BasicNameValuePair("password", "123456"));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源  
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public void post() {
        // 创建默认的httpClient实例.  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost  
        HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
        // 创建参数队列  
        List formparams = new ArrayList();
        formparams.add(new BasicNameValuePair("type", "house"));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源  
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 发送 get请求
     */
    public void get() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.  
            HttpGet httpget = new HttpGet("http://www.baidu.com/");
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.  
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体  
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态  
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度  
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容  
                    System.out.println("Response content: " + EntityUtils.toString(entity));
                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源  
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 上传文件
     */
    public void upload() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
 
            FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
 
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
 
            httppost.setEntity(reqEntity);
 
            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

本实例是采用HttpClient4.3版本。

参考网址:

https://blog.csdn.net/wangpeng047/article/details/19624529

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-06-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
《Linux高性能服务器编程》学习小结3
下面的每一个logical指定一个实际运行着的服务器,如前面小结1 2 中所述的多进程或者多线程服务器;三个字段分别指定:服务器的ip4地址,服务器服务端口,以及进程池中的进程与这个服务器保持多少个连接;
wanyicheng
2021/02/04
3.1K0
《Linux高性能服务器编程》学习小结3
[apue] 如何处理 tcp 紧急数据(OOB)?
在上大学的时候,我就听说了 OOB 这个概念(Out Of Band 带外数据,又称紧急数据)。当时老师给的解释就是在当前处理的数据流之外的数据,用于紧急的情况。然后就没有然后了……
海海
2022/08/19
9320
2-UNIX网络编程-进阶学习前的基础知识储备
诚实点,并不是假设读的人C语言基础很差,而事实是,自己的C语言基础实在太差,要补学基础知识之后才可以进行后续的学习,惭愧!
zoujunjie202
2022/07/27
4200
2-UNIX网络编程-进阶学习前的基础知识储备
网络编程 - Linux Socket编程
  socket(套接字)是网络编程编程的一种技巧。通过socket不仅可以实现跨进程通信,还可以实现跨主机的网络通信。使用这种技术,就可以实现全国各地的通讯。例如:深圳的一台电脑接收来自北京一台电脑发来的信息。   本篇不涉及太底层的网络原理,仅说明socket的基本使用方法。主要参考《Linux网络编程》。本篇源码获取方式见文底小字。
开源519
2023/03/09
9.9K0
网络编程 - Linux Socket编程
UNIX(进程间通信):17 深入理解unix域
unix域协议并不是一个实际的协议族,而是在单个主机上执行客户/服务器通信的一种方法。
用户3479834
2021/03/04
1.8K0
UNIX(进程间通信):17 深入理解unix域
【Linux】:Socket编程 TCP
在上篇文章里面已经讲了关于 Socket UDP 网络编程的内容,这篇文章我们主要是关于 Socket TCP 网络编程的内容
IsLand1314
2025/01/20
2430
【Linux】:Socket编程 TCP
C/C++ 实现正反向端口映射
通常服务器是放在内网中,内部局域网中,并且分配了私有IP地址,而如果想要在外部直接访问内部服务器则需要端口映射,端口映射也叫做端口转发,或者叫做虚拟服务器,在渗透时当我们拿到目标机器权限以后,目标机器实在内网环境中,如果想要外部直接访问内部的特定机器的特定端口,则需要使用映射来实现,常用的映射工具是LCX,或者自己实现。
王瑞MVP
2022/12/28
6510
Socket
Socket模块简单理解就是对socket套接字的封装,当然不是简单的对socket套接字接口的封装,还需要实现一些方法,比如启动非阻塞通信、创建客户端连接、创建服务器连接等。
二肥是只大懒蓝猫
2024/02/07
1700
Socket
加密通讯协议SSL编程周立发
编译程序用下列命令: gcc -Wall ssl-client.c -o client gcc -Wall ssl-server.c -o server 运行程序用如下命令: ./server 7838 1 127.0.0.1 cacert.pem privkey.pem ./client 127.0.0.1 7838 用下面这两个命令产生上述cacert.pem和privkey.pem文件: openssl genrsa -out privkey.pem 2048 openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095 具体请参考 “OpenSSL体系下使用密钥数字证书等” 如果想对SSL有更深入的了解,请学习计算机安全相关的内容,尤其是非对称加密技术。 如果想对SSL库的源代码有深入学习,请去 www.openssl.org 下载源码来阅读。
一见
2018/08/07
1.4K0
Unix域协议学习小结
Unix域协议不是一个真正意义上的协议族,只是一个利用socket api在单个主机上进行进程间通信的方法。它不需要走传统网络协议栈,也就不需要计算校验和、维护序列号以及应答等操作。
chain
2018/06/12
2.1K4
Librdkafka的Transport层
rd_kafka_recv按kafka的协议来收包, 先收4字节,拿到payload长度, 再根据这个长度收够payload内容, 这样一个完整的response就接收到了
扫帚的影子
2018/09/05
1.5K0
UDP&TCP Linux网络应用编程详解
暂时想不出什么好的应用场景, 目前想到目标就是实现让两个设备通过网络传输数据, 比如开发板和Linux主机之间传数据, 以后就可以实现开发板通过网络上报数据或者主机通过网络控制开发板。
韦东山
2020/09/30
5.8K0
UDP&TCP Linux网络应用编程详解
[apue] 作为 daemon 启动, Unix Domain Socket 侦听失败?
前段时间写一个传递文件句柄的小 demo,有 server 端、有 client 端,之间通过 Unix Domain Socket 通讯。
海海
2022/08/19
3250
【在Linux世界中追寻伟大的One Piece】Socket编程TCP(续)
枫叶丹
2024/11/04
980
从零开始的C++网络编程
导语:本文主要介绍如何从零开始搭建简单的C++客户端/服务器,并进行简单的讲解和基础的压力测试演示。该文章相对比较入门,主要面向了解计算机网络但未接触过网络编程的同学。 本文主要分为四个部分: 搭建C/S:用C++搭建一个最简单的,基于socket网络编程的客户端和服务器 socket库函数浅析:基于上一节搭建的客户端和服务器的代码介绍相关的库函数 搭建HTTP服务器:基于上一节的介绍和HTTP工作过程将最开始搭建的服务器改为HTTP服务器 压力测试入门:优化一下服务器,并使用ab工具对优化前后的
腾讯技术工程官方号
2019/10/23
8K1
从零开始的C++网络编程
Linux Tcp通信——服务器与客户端
之前一直想做linux+qt方向的,然而现在变成嵌入式软件方向了。其实也还好吧,这样就需要对底层的一些东西了解,目前是智能交通行业了。
用户5908113
2020/05/28
7K0
TCP服务器和客户端基础功能实现和要点解析
tankaro
2025/01/23
1290
一个工业级、跨平台、轻量级的 tcp 网络服务框架:gevent
作为公司的公共产品,经常有这样的需求:就是新建一个本地服务,产品线作为客户端通过 tcp 接入本地服务,来获取想要的业务能力。与印象中动辄处理成千上万连接的 tcp 网络服务不同,这个本地服务是跑在客户机器上的,Win32 上作为开机自启动的 windows 服务运行;Linux 上作为 daemon 在后台运行。总的说来就是用于接收几个产品进程的连接,因此轻量化是其最重要的要求,在这个基础上要能兼顾跨平台就可以了。其实主要就是 windows,再兼顾一点儿 linux。
海海
2022/08/19
1.2K0
一个工业级、跨平台、轻量级的 tcp 网络服务框架:gevent
linux 下经典 IO 复用模型 -- epoll 的使用
epoll 是 linux 内核为处理大批量文件描述符而对 poll 进行的改进版本,是 linux 下多路复用 IO 接口 select/poll 的增强版本,显著提高了程序在大量并发连接中只有少量活跃的情况下的CPU利用率。 在获取事件时,它无需遍历整个被侦听描述符集,只要遍历被内核 IO 事件异步唤醒而加入 ready 队列的描述符集合就行了。 epoll 除了提供 select/poll 所提供的 IO 事件的电平触发,还提供了边沿触发,,这样做可以使得用户空间程序有可能缓存 IO 状态,减少 epoll_wait 或 epoll_pwait 的调用,提高程序效率。
用户3147702
2022/06/27
7220
linux 下经典 IO 复用模型 -- epoll 的使用
epoll 基于非阻塞I/O事件驱动
该程序来源于传智博客教师课件,本人只是自己对照着写了一遍并做了注释,该模型可以承载大量客户端的连接二不会出现卡顿等情况,前提是我们交互的数据很少,如果交互数据较大,该例子还是有些小问题的。大家可以自己拓展,配合多线程可以实现大数据多客户端连接传输的程序。具体代码如下:
我与梦想有个约会
2023/10/20
2070
相关推荐
《Linux高性能服务器编程》学习小结3
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档