spring boot中 使用http请求

因为项目需求,需要两个系统之间进行通信,经过一番调研,决定使用http请求。
服务端没有什么好说的,本来就是使用web 页面进行访问的,所以spring boot启动后,controller层的接口就自动暴露出来了,客户端通过调用对应的url即可,所以这里主要就客户端。
首先我自定义了一个用来处理http 请求的工具类DeviceFactoryHttp,
既然是url访问,那就有两个问题需要处理,一个请求服务的url,和请求服务端的参数,客户端的消息头
请求服务的url:请求服务端url我定义的是跟客户端一个样的url
服务端的参数:服务端的参数有两种一种经过封装的,类似下面这样:
http://localhost:8080/switch/getAllStatus?data{"interface name”:”getAllStudentStaus”}
一种是没有经过封装的,类似下面这样:
http://localhost:8080/switch/getStudentInfoByName?name=zhangSan
首先是经过封装:
一:初始化httpclient
private static HttpClient client = null;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(128);
cm.setDefaultMaxPerRoute(128);
client = HttpClients.custom().setConnectionManager(cm).build();
}
二:获取请求的url,因为我服务端定义的url与客户端一样,所以我直接使用请求客户端的url
//根据request获取请求的url
public  StringBuffer getUrlToRequest(HttpServletRequest request) {
StringBuffer url=request.getRequestURL();//获取请求的url(http://localhost:8080/switch/getStudentInfoByName)
String[] splitArr=url.toString().split("/");
String appName=splitArr[3];//项目名称
String ipReport=splitArr[2];//项目ip:report
String resultStr=url.toString().replaceAll(appName,DevFacConstans.facname).replaceAll(ipReport, DevFacConstans.ip+":"+DevFacConstans.report);
return new StringBuffer(resultStr);
}
获取url根据/ 进行split,因为我这是测试环境,生产环境ip,端口号(域名)肯定不是localhost,有的前面还会加上项目名称,
所以我split对应的值来进行替换。
三:拼装请求参数,调用http请求
/**
* 发送http请求 有request
* 给controller层调用
* @param request
* @return
*/
public String sendHttpToDevFac(HttpServletRequest request)throws Exception {
HttpClient client = null;
String returnResult="";
// http://localhost:8080/leo/1.0/h5/login
StringBuffer urlBuffer=getUrlToRequest(request);//调用第二步,获取url
//获取参数并拼装
String dataAsJson = request.getParameter("data");
String encoderData=URLEncoder.encode(dataAsJson,"utf-8");
HttpGet get=new HttpGet(urlBuffer.append("?data=").append(encoderData).toString());
//set headers
Enumeration<String> headerNames=request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName=headerNames.nextElement();
String headerValue=request.getHeader(headerName);
get.setHeader(headerName, headerValue);
}
client=DeviceFactoryHttp.client;
logger.info("开始调用http请求,请求url:"+urlBuffer.toString());
HttpResponse rep=client.execute(get);
returnResult=EntityUtils.toString(rep.getEntity(),"utf-8");
logger.info("http 请求调用结束!!");
return returnResult;
}
先获取请求的参数,再将参数拼装在url后面,URLEncoder.encode 这个不要忘了,因为参数会有一些符号,需要对参数进行编码后再加入url,否则就会抛出异常,
set headers:因为有部分信息服务端会从请求头中取出,所以我将客户端的请求头也set到服务端的request中,请求的url和请求的参数拼好就就可以client.exceute(get)执行请求了。
上面的是我浏览器直接将request请求作为参数传到我客户端,我所以我可以直接从request中获取url,有的是没有request,就需要从request的上下文环境中取了。
没有经过封装的:
首先从上下文中获取request的
/**
* 获取request
* @return
*/
public static HttpServletRequest getRequest(){
  ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  HttpServletRequest request ra.getRequest();
  return request;
}
二:有了request后,就有了url,下面再来解析请求参数,因为这个参数是没有封装的,所以获取所有的请求参数
/*** 没有request 请求,给controller层调用* @param key* @param interfaceName* @param strings* @return* @throws Exception*/public String centerToDeviceFacNoRequest(String key,String interfaceName)throws Exception {try {HttpServletRequest request=getRequest();//上面第一步,从上下文中获取url//获取reuquest请求参数Enumeration<String> names=  request.getParameterNames();Map<String,String>paramMap=new HashMap<>();//遍历请求mapwhile(names.hasMoreElements()) {String name=names.nextElement();String value=(String) request.getParameter(name);paramMap.put(name, value);}//调用发送http请求的方法return sendHttpToDevFacNoData(paramMap,request);} catch (Exception e) {e.printStackTrace();}//endreturn null;}

 

三:发送http请求
/*** 发送http请求,【没有data数据的】* @return*/public String sendHttpToDevFacNoData(Map<String,String>paramMap,HttpServletRequest request)throws Exception {HttpClient client = null;String result="";StringBuffer dataBuffer=getUrlToRequest(request);//获取urldataBuffer.append("?");client=DeviceFactoryHttp.client;Iterator<Entry<String, String>> paamIt=paramMap.entrySet().iterator();while(paamIt.hasNext()) {Entry<String, String> entry=paamIt.next();dataBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");}String resultUrl=dataBuffer.toString().substring(0, dataBuffer.toString().lastIndexOf("&"));//发送请求HttpGet get=new HttpGet(resultUrl);//set headersEnumeration<String> headerNames=request.getHeaderNames();while(headerNames.hasMoreElements()) {String headerName=headerNames.nextElement();String headerValue=request.getHeader(headerName);get.setHeader(headerName, headerValue);}HttpResponse rep=client.execute(get);logger.info("开始调用http请求,请求url:"+resultUrl);//返回结果result=EntityUtils.toString(rep.getEntity(),"utf-8");logger.info(" http 请求调用结束!!");return result;}

 

转载于:https://www.cnblogs.com/zhangXingSheng/p/7745009.html

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

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

相关文章

arduino joy_如何用Joy开发Kubernetes应用

arduino joyLet’s face it: Developing distributed applications is painful.让我们面对现实&#xff1a;开发分布式应用程序很痛苦。 Microservice architectures might be great for decoupling and scalability but they are intimidatingly complex when it comes to de…

怎么样得到平台相关的换行符?

问题&#xff1a;怎么样得到平台相关的换行符&#xff1f; Java里面怎么样得到平台相关的换行符。我不可能到处都用"\n" 回答一 In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting me…

scrapy常用工具备忘

scrapy常用的命令分为全局和项目两种命令&#xff0c;全局命令就是不需要依靠scrapy项目&#xff0c;可以在全局环境下运行&#xff0c;而项目命令需要在scrapy项目里才能运行。一、全局命令##使用scrapy -h可以看到常用的全局命令 [rootaliyun ~]# scrapy -h Scrapy 1.5.0 - n…

机器学习模型 非线性模型_机器学习:通过预测菲亚特500的价格来观察线性模型的工作原理...

机器学习模型 非线性模型Introduction介绍 In this article, I’d like to speak about linear models by introducing you to a real project that I made. The project that you can find in my Github consists of predicting the prices of fiat 500.在本文中&#xff0c;…

NOIP赛前模拟20171027总结

题目&#xff1a; 1.寿司 给定一个环形的RB串要求经过两两互换后RB分别形成两段连续区域,求最少操作次数(算法时间O(n)) 2.金字塔 给定一个金字塔的侧面图有n层已知每一层的宽度高度均为1要求在图中取出恰好K个互不相交的矩形&#xff08;边缘可以重叠&#xff09;,求最多可以取…

虚幻引擎 js开发游戏_通过编码3游戏学习虚幻引擎4-5小时免费游戏开发视频课程

虚幻引擎 js开发游戏One of the most widely used game engines is Unreal Engine by Epic Games. On the freeCodeCamp.org YouTube channel, weve published a comprehensive course on how to use Unreal Engine with C to develop games.Epic Games的虚幻引擎是使用最广泛的…

建造者模式什么时候使用?

问题&#xff1a;建造者模式什么时候使用&#xff1f; 建造者模式在现实世界里面的使用例子是什么&#xff1f;它有啥用呢&#xff1f;为啥不直接用工厂模式 回答一 下面是使用这个模式的一些理由和Java的样例代码&#xff0c;但是它是由设计模式的4个人讨论出来的建造者模式…

TP5_学习

2017.10.27&#xff1a;1.index入口跑到public下面去了 2.不能使用 define(BIND_MODULE,Admin);自动生成模块了&#xff0c;网上查了下&#xff1a; \think\Build::module(Admin);//亲测,可用 2017.10.28:1.一直不知道怎么做查询显示和全部显示&#xff0c;原来如此简单&#x…

sql sum语句_SQL Sum语句示例说明

sql sum语句SQL中的Sum语句是什么&#xff1f; (What is the Sum statement in SQL?) This is one of the aggregate functions (as is count, average, max, min, etc.). They are used in a GROUP BY clause as it aggregates data presented by the SELECT FROM WHERE port…

10款中小企业必备的开源免费安全工具

10款中小企业必备的开源免费安全工具 secist2017-05-188共527453人围观 &#xff0c;发现 7 个不明物体企业安全工具很多企业特别是一些中小型企业在日常生产中&#xff0c;时常会因为时间、预算、人员配比等问题&#xff0c;而大大减少或降低在安全方面的投入。这时候&#xf…

为什么Java里面没有 SortedList

问题&#xff1a;为什么Java里面没有 SortedList Java 里面有SortedSet和SortedMap接口&#xff0c;它们都属于Java的集合框架和提供对元素进行排序的方法 然鹅&#xff0c;在我的认知里Java就没有SortedList这个东西。你只能使用java.util.Collections.sort()去排序一个list…

图片主成分分析后的可视化_主成分分析-可视化

图片主成分分析后的可视化If you have ever taken an online course on Machine Learning, you must have come across Principal Component Analysis for dimensionality reduction, or in simple terms, for compression of data. Guess what, I had taken such courses too …

回溯算法和递归算法_回溯算法:递归和搜索示例说明

回溯算法和递归算法Examples where backtracking can be used to solve puzzles or problems include:回溯可用于解决难题或问题的示例包括&#xff1a; Puzzles such as eight queens puzzle, crosswords, verbal arithmetic, Sudoku [nb 1], and Peg Solitaire. 诸如八个皇后…

C#中的equals()和==

using System;namespace EqualsTest {class EqualsTest{static void Main(string[] args){//值类型int x 1;int y 1;Console.WriteLine(x y);//TrueConsole.WriteLine(x.Equals(y));//True //引用类型A a new A();B b new B();//Console.WriteLine(ab);//报错…

JPA JoinColumn vs mappedBy

问题&#xff1a;JPA JoinColumn vs mappedBy 两者的区别是什么呢 Entity public class Company {OneToMany(cascade CascadeType.ALL , fetch FetchType.LAZY)JoinColumn(name "companyIdRef", referencedColumnName "companyId")private List<B…

TP引用样式表和js文件及验证码

TP引用样式表和js文件及验证码 引入样式表和js文件 <script src"__PUBLIC__/bootstrap/js/jquery-1.11.2.min.js"></script> <script src"__PUBLIC__/bootstrap/js/bootstrap.min.js"></script> <link href"__PUBLIC__/bo…

pytorch深度学习_深度学习和PyTorch的推荐系统实施

pytorch深度学习The recommendation is a simple algorithm that works on the principle of data filtering. The algorithm finds a pattern between two users and recommends or provides additional relevant information to a user in choosing a product or services.该…

什么是JavaScript中的回调函数?

This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.本文简要介绍了JavaScript编程语言中的回调函数的概念和用法。 函数就是对象 (Functions are Objects) The first thing we need to know i…

Java 集合-集合介绍

2017-10-30 00:01:09 一、Java集合的类关系图 二、集合类的概述 集合类出现的原因&#xff1a;面向对象语言对事物的体现都是以对象的形式&#xff0c;所以为了方便对多个对象的操作&#xff0c;Java就提供了集合类。数组和集合类同是容器&#xff0c;有什么不同&#xff1a;数…

为什么Java不允许super.super.method();

问题&#xff1a;为什么Java不允许super.super.method(); 我想出了这个问题&#xff0c;认为这个是很好解决的&#xff08;也不是没有它就不行的&#xff09;如果可以像下面那样写的话&#xff1a; Override public String toString() {return super.super.toString(); }我不…