关于java:在Java中使用HttpUtils实现发送HTTP请求

44次阅读

共计 5700 个字符,预计需要花费 15 分钟才能阅读完成。

微信公众号:冯文议(ID:fwy-world)

HTTP 申请,在日常开发中,还是比拟常见的,明天给大家分享 HttpUtils 如何应用。

浏览本文,你将播种:

  • 简略总结 HTTP 申请罕用配置;
  • JavaLib 中 HttpUtils 如何应用;
  • 如何封装 HTTP 申请工具类。

第一局部:简略总结 HTTP 申请罕用配置

大家好,在 Java 开发中,常常遇到须要调用第三方提供的接口服务,常见的模式是 HTTP + JSON,上面,就对 http 申请常见的设置,做一个阐明

http 提供多种申请形式,以满足咱们日常须要,先按申请形式来做阐明:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

在 RESTful API 开发中,咱们能够依据这些申请形式设计咱们的 API 接口。举例:

  • GET:获取资源
  • POST:提交资源
  • PUT:更新残缺资源
  • PATCH:更新局部资源
  • DELETE:删除资源

参数格局

  • form 表单
  • json

其余

  • 超时工夫设置

第二局部:应用 JavaLib 的 HttpUtils

简略的 get 申请

System.out.println(HttpUtils.get("https://www.baidu.com"));

响应后果:

通过简略尝试,证实两点:

  • 一是,这个还是能够应用的;
  • 二是,原来应用如此简略。

如果要你手写一个 http 申请,或者你脑海里一篇空白,会去搜寻各种材料。

咱们再试一个简单的

接口:

接口地址:https://erwin-api.fengwenyi.com/erwin/blog/page
申请办法:GET
参数:currentPage,pageSize
参数格局:form
响应:application/json

String url = "https://erwin-api.fengwenyi.com/erwin/bookmark/page?currentPage=1&pageSize=10";

Request request = new Request();
request.setUrl(url);
request.setMethod(Request.Method.GET);

Map<String, String> headerMap = new HashMap<>();
headerMap.put("Accept", "application/json");

Request.Option option = new Request.Option();
option.setHeaders(headerMap);

try {System.out.println(HttpUtils.execute(request, option));
} catch (IOException e) {throw new RuntimeException(e);
}

响应后果:

{
    "code":"SUCCESS",
    "message":"Success",
    "success":true,
    "header":null,
    "body":{
        "currentPage":1,
        "pageSize":10,
        "totalRows":661,
        "totalPages":67,
        "content":[
            {
                "id":"1634772578877935617",
                "timestamp":1678595130000,
                "enabledState":null,
                "name":"VScode 中文显示呈现黄色方框的解决办法_vscode 汉字被框住_YJer 的博客 -CSDN 博客",
                "url":"https://blog.csdn.net/qq_33249042/article/details/123252625",
                "icon":null,
                "classifyName":"软件",
                "classifyId":"1522587269600481281"
            },
            {
                "id":"1632640455110922241",
                "timestamp":1678086792000,
                "enabledState":null,
                "name":"Spring 中 init-method 和 destroy-method 的四种形式_星夜孤帆的博客 -CSDN 博客",
                "url":"https://blog.csdn.net/qq_38826019/article/details/117387398",
                "icon":null,
                "classifyName":"Spring",
                "classifyId":"1522586360887742466"
            },
            {
                "id":"1631597310596190209",
                "timestamp":1677838087000,
                "enabledState":null,
                "name":"vue3 + elemenplus 实现导航栏 - 掘金",
                "url":"https://juejin.cn/post/7084871748608327687",
                "icon":null,
                "classifyName":"前端",
                "classifyId":"1525554881275990018"
            },
            {
                "id":"1631593154401636354",
                "timestamp":1677837096000,
                "enabledState":null,
                "name":"Spring bean 创立过程源码解析 - 腾讯云开发者社区 - 腾讯云",
                "url":"https://cloud.tencent.com/developer/article/1631160",
                "icon":null,
                "classifyName":"Spring",
                "classifyId":"1522586360887742466"
            },
            {
                "id":"1631592987673858050",
                "timestamp":1677837056000,
                "enabledState":null,
                "name":"SpringBoot 之容器启动源码剖析与 Bean 加载_springboot 加载 bean 源码_minemine0418 的博客 -CSDN 博客",
                "url":"https://blog.csdn.net/minemine0418/article/details/102308912",
                "icon":null,
                "classifyName":"Spring Boot",
                "classifyId":"1522586446766116865"
            },
            {
                "id":"1631586585454678018",
                "timestamp":1677835530000,
                "enabledState":null,
                "name":"Spring-Bean 生命周期 - 知乎",
                "url":"https://zhuanlan.zhihu.com/p/158468104",
                "icon":null,
                "classifyName":"Spring",
                "classifyId":"1522586360887742466"
            },
            {
                "id":"1631579732104548354",
                "timestamp":1677833896000,
                "enabledState":null,
                "name":"一文读懂 Spring Bean 的生命周期_spring bean 的生命周期_老周聊架构的博客 -CSDN 博客",
                "url":"https://blog.csdn.net/riemann_/article/details/118500805",
                "icon":null,
                "classifyName":"Spring",
                "classifyId":"1522586360887742466"
            },
            {
                "id":"1630768897186697218",
                "timestamp":1677640578000,
                "enabledState":null,
                "name":"MySQL 同时统计多个条件的记录条数_ztnhnr 的博客 -CSDN 博客",
                "url":"https://blog.csdn.net/ztnhnr/article/details/107165942",
                "icon":null,
                "classifyName":"MySQL",
                "classifyId":"1522586805693681666"
            },
            {
                "id":"1630768792098410497",
                "timestamp":1677640553000,
                "enabledState":null,
                "name":"sql 查问近七天,近两周,近一个月的数据_sql 最近一周数据_心诚则灵'的博客 -CSDN 博客",
                "url":"https://blog.csdn.net/wenchangwenliu/article/details/119891790",
                "icon":null,
                "classifyName":"MySQL",
                "classifyId":"1522586805693681666"
            },
            {
                "id":"1630480535938764801",
                "timestamp":1677571827000,
                "enabledState":null,
                "name":"开源流程引擎哪个好,如何选型?- 知乎",
                "url":"https://zhuanlan.zhihu.com/p/369761832",
                "icon":null,
                "classifyName":"Java",
                "classifyId":"1522586296119300097"
            }
        ]
    }
}

响应后果,还是合乎预期的。

当然,HTTP 还有其余,比方超时等等,上面看看完整版的申请示例:

Map<String, Object> paramMap = new HashMap<>();
paramMap.put("currentPage", 1);
paramMap.put("pageSize", 10);

Map<String, String> headerMap = new HashMap<>();
headerMap.put("Accept", "application/json");

Request request = new Request();
request.setUrl("https://erwin-api.fengwenyi.com/erwin/bookmark/page");
request.setParam(paramMap);
request.setMethod(Request.Method.GET);
request.setUtil(Request.Util.OkHttp);

Request.Option option = new Request.Option();
option.setHeaders(headerMap);
option.setConnectTimeoutSecond(3);
option.setReadTimeoutSecond(5);
option.setLogLevel(Request.LogLevel.DEBUG);

try {String result = HttpUtils.execute(request, option);
    System.out.println(result);
} catch (IOException e) {throw new RuntimeException(e);
}

响应后果也是跟下面一样的。

第三局部:分享 HttpUtils 是如何封装的

首先是 RequestResponse 对应 HTTP 的申请和响应,包门路如下:

  • com.fengwenyi.javalib.http.Request
  • com.fengwenyi.javalib.http.Response

另外,com.fengwenyi.javalib.http.Request.Option 来寄存 HTTP 参数配置。

这一部分的思路起源是 Spring Cloud OpenFeign。

为了兼容多种 HTTP 工具实现申请,引入了 HttpClientFactory,其余工具类,只有实现 HttpClient 接口,就行。

  • com.fengwenyi.javalib.http.client.HttpClient
  • com.fengwenyi.javalib.http.client.HttpClientFactory

欧克,上面咱们就以代码来看看:

HttpUtils#execute

public static String execute(Request request, Request.Option option) throws IOException {check(request);
    HttpClient httpClient = HttpClientFactory.get(request.getUtil());
    Response response = httpClient.execute(request, option);
    return handleResponse(response);
}

HttpClientFactory#get

public static HttpClient get(Request.Util httpUtil) {if (Request.Util.JDK == httpUtil) {return new JdkHttpClient();
    } else if (Request.Util.OkHttp == httpUtil) {return new OkHttpClient();
    } else {throw new RuntimeException("not find http util:" + httpUtil.name());
    }
}

所以,只须要实现 HttpClient#execute 接口就行。

Response execute(Request request, Request.Option option) throws IOException;

源码:https://github.com/fengwenyi/JavaLib


好了,明天的分享就到这里了。我是小冯,一名 Java 程序员,专一于程序设计和开发,如果你在开发上遇到问题,欢送一起交换,微信公众号:冯文议(ID:fwy-world)。

正文完
 0