Java开发小技巧(五):HttpClient工具类

摘要:
前言大多数Java应用程序调用接口,通过HTTP协议访问各种网络资源。JDK还提供了相应的HTTP工具包,但使用起来并不方便和灵活。因此,我们可以使用ApacheHttpClient封装一个具有访问HTTP协议的基本功能的高效工具类,这为后续开发和使用提供了方便。

Java开发小技巧(五):HttpClient工具类第1张

前言

大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具有访问HTTP协议基本功能的高效工具类,为后续开发使用提供方便。

文章要点:

  • HttpClient使用流程
  • 工具类封装
  • 使用实例

HttpClient使用流程

1、导入Maven依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

2、创建HttpClient实例

HttpClient client = HttpClientBuilder.create().build();

3、创建请求方法的实例

GET请求使用HttpGet,POST请求使用HttpPost,并传入请求的URL

// POST请求
HttpPost post = new HttpPost(url);
// GET请求,URL中带请求参数
HttpGet get = new HttpGet(url);

4、添加请求参数

普通形式

List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username", "admin"));
list.add(new BasicNameValuePair("password", "123456"));

// GET请求方式
// 由于GET请求的参数是拼装在URL后方,所以需要构建一个完整的URL,再创建HttpGet实例
URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com");
uriBuilder.setParameters(list);
HttpGet get = new HttpGet(uriBuilder.build());

// POST请求方式
post.setEntity(new UrlEncodedFormEntity(list, Charsets.UTF_8));

JSON形式

Map<String,String> map = new HashMap<>();
map.put("username", "admin");
map.put("password", "123456");
Gson gson = new Gson();
String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType());
post.setEntity(new StringEntity(json, Charsets.UTF_8));
post.addHeader("Content-Type", "application/json");

5、发送请求

调用HttpClient实例的execute方法发送请求,返回一个HttpResponse对象

HttpResponse response = client.execute(post);

6、获取结果

String result = EntityUtils.toString(response.getEntity());

7、释放连接

post.releaseConnection();

工具类封装

HttpClient工具类代码(根据相应使用场景进行封装):

public class HttpClientUtil {
    // 发送GET请求
    public static String getRequest(String path, List<NameValuePair> parametersBody) throws RestApiException, URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(path);
        uriBuilder.setParameters(parametersBody);
        HttpGet get = new HttpGet(uriBuilder.build());
        HttpClient client = HttpClientBuilder.create().build();
        try {
            HttpResponse response = client.execute(get);
            int code = response.getStatusLine().getStatusCode();
            if (code >= 400)
                throw new RuntimeException((new StringBuilder()).append("Could not access protected resource. Server returned http code: ").append(code).toString());
            return EntityUtils.toString(response.getEntity());
        }
        catch (ClientProtocolException e) {
            throw new RestApiException("postRequest -- Client protocol exception!", e);
        }
        catch (IOException e) {
            throw new RestApiException("postRequest -- IO error!", e);
        }
        finally {
            get.releaseConnection();
        }
    }

    // 发送POST请求(普通表单形式)
    public static String postForm(String path, List<NameValuePair> parametersBody) throws RestApiException {
        HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8);
        return postRequest(path, "application/x-www-form-urlencoded", entity);
    }

    // 发送POST请求(JSON形式)
    public static String postJSON(String path, String json) throws RestApiException {
        StringEntity entity = new StringEntity(json, Charsets.UTF_8);
        return postRequest(path, "application/json", entity);
    }

    // 发送POST请求
    public static String postRequest(String path, String mediaType, HttpEntity entity) throws RestApiException {
        logger.debug("[postRequest] resourceUrl: {}", path);
        HttpPost post = new HttpPost(path);
        post.addHeader("Content-Type", mediaType);
        post.addHeader("Accept", "application/json");
        post.setEntity(entity);
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            if (code >= 400)
                throw new RestApiException(EntityUtils.toString(response.getEntity()));
            return EntityUtils.toString(response.getEntity());
        }
        catch (ClientProtocolException e) {
            throw new RestApiException("postRequest -- Client protocol exception!", e);
        }
        catch (IOException e) {
            throw new RestApiException("postRequest -- IO error!", e);
        }
        finally {
            post.releaseConnection();
        }
    }
}

使用实例

GET请求

List<NameValuePair> parametersBody = new ArrayList();
parametersBody.add(new BasicNameValuePair("userId", "admin"));
String result = HttpClientUtil.getRequest("http://www.test.com/user",parametersBody);

POST请求

List<NameValuePair> parametersBody = new ArrayList();
parametersBody.add(new BasicNameValuePair("username", "admin"));
parametersBody.add(new BasicNameValuePair("password", "123456"));
String result = HttpClientUtil.postForm("http://www.test.com/login",parametersBody);

POST请求(JSON形式)

Map<String,String> map = new HashMap<>();
map.put("username", "admin");
map.put("password", "123456");
Gson gson = new Gson();
String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType());
String result = HttpClientUtil.postJSON("http://www.test.com/login", json);

关于HttpClient的详细介绍看这里:HttpClient入门

本文为作者kMacro原创,转载请注明来源:https://zkhdev.github.io/2018/10/12/java_dev5/

免责声明:文章转载自《Java开发小技巧(五):HttpClient工具类》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇nRF52832 开发记录(一)Win10+VS2017配置pthread下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

delphi2009及以上版本中String与PAnsiChar转换

相关资料: http://blog.sina.com.cn/s/blog_140f86bd70102xs49.html   在winsock编程中,使用api函数 inet_addr将ip地址转换成网络字节序时,传入参数类型为直接将string转换成PAnsiChar类型,转换出来的网络字节有错误,无法使用该ip,解决办法如下: 所有的原生字符串类型S...

JDBC实现从数据库中读取信息以表格的形式展示

方法都是通用的,要看你如何去灵活的运用!!! 本文以“新闻发布系统”为例 第一步:建立数据库(使用的是mysql数据库) 其中数据库信息为: 数据库名:news 表名:title,字段名分别为(序号、标题名称、创建者、创建时间) create table title( id int(2) primary key, name varchar(20), cre...

把大文件切割成小文件

package com.jm.label.tools;/*** 把大文件切割成小文件*/import java.io.File;import java.io.FileInputStream; import java.io.FileNotFoundException;import java.io.FileOutputStream; import java.io...

【java虚拟机】jvm内存模型

作者:pengjunlee原文链接:https://blog.csdn.net/pengjunlee/article/details/71909239 目录 一、运行时数据区域   1、程序计数器   2、Java 虚拟机栈   3、本地方法栈   4、Java 堆   5、方法区   6、运行时常量池   7、直接内存 二、OutOfMemoryErro...

delphi 对应 c# 的一些函数及类型的转换方法【原】

例一 实现目的:将字符串中每一个字符转成二进制(比如 'Data' 中的 D 转成 00100010 ,整个就是 00100010100001100010111010000110) 处理逻辑:string result = StrToByte("Data"); result结果是00100010100001100010111010000110   1、实际...

pm grant 命令

CustomLocale.apk所需要的权限"android.permission.CHANGE_CONFIGURATION"自Android 4.2,4.2.2起系统定义为android:protectionLevel="signature|system|development",这就需要在已root的android设置上运行命令: adb shell...