美文网首页
Spring模拟HTTP请求

Spring模拟HTTP请求

作者: 此处有熊 | 来源:发表于2019-10-18 00:06 被阅读0次

最近做mina相关的项目,服务端使用mina作为中转服务器,需要将设备端发起的tcp请求中转到后端HttpServer,此时mina端相对于后端HttpServer是一个Httpclient,参阅前辈们写的代码,大致了解其使用的技术。

   项目中使用的实际上是使用Spring框架中的RestTemplate,使用比较简单,先声明实例化再调用对应接口。具体如下:

    RestTemplate的声明:

    1、RestTemplate会在String启动时注册成bean所以第一种方式是直接注入获取RestTemplate对象。

如:

@Autowired

RestTemplate restTemplate;

    2、 RestTemplate提供了无参构造方法,可以直接new。

     如:RestTemplate template = new RestTemplate();

    RestTemplate的使用:

    由于RestTemplate类的主要方法使用都大同小异,这里仅拿postForObject方法进行举例。

postForObject方法是进行一次post请求返回一个任意对象(Spring会将返回值自动序列化),

postForObject方法有3个及3个以上参数,但仅使用3个参数已经可以满足日常需要。

template.posForObject(String url地址,Object  传递参数,Class 返回值映射对象)

其中

url地址:必须为全限定地址如http://www.baidu.com/,

传递参数:必须使用 MultiValueMap对象(其实可以使用其他对象但有些对象是不会将参数请求进去比如Map,尚不清楚原理,如果有大神知道还请告知)

MultiValueMap对象的泛型为<String,List>其他泛型使用都会报错。其他使用方式参考Map

返回值映射对象:可以使用Object,Map,String等,Spring强大的序列化映射机制会将返回文件映射成任何可以映射的类型

当返回文件不能转换为返回值映射对象时会报序列化异常

返回值:返回值类型为返回值映射对象类型。

    示例:

String url = webApiBaseUrl + "sendStaffApi/getStaffInfoBySn.shtml?sn="+sn;

Map<String, String> params = new HashMap<>();

HttpHeaders headers = new HttpHeaders();

params.put("sn", sn);

RestTemplate template = new RestTemplate();

ResponseEntity<String> response = template.exchange(url, HttpMethod.POST, new HttpEntity<String>(headers),

String.class, params);

//返回数据结果

String result = response.getBody();

相关文章

  • Spring模拟HTTP请求

    最近做mina相关的项目,服务端使用mina作为中转服务器,需要将设备端发起的tcp请求中转到后端HttpServ...

  • SpringBoot单元测试

    1、Spring Boot的单元测试 依赖Maven配置 示例代码 2、MockMvc模拟Http请求测试 使用说...

  • 模拟Http请求

    使用Telnet模拟Http请求 打开cmd运行框,输入Telnet www.baidu.com 80后按回车键。...

  • Java模拟Http请求

    本文使用的是org.apache.httpcomponents中的httpclient,因为post请求涉及到传输...

  • 自动模拟HTTP请求

    客户端如果要与服务器端进行通信,需要通过http请求进行,http请求有很多种,主要的有post和get两种请求方...

  • postman模拟HTTP请求

    APP开发过程中,手机端与服务端由不同 的人员负责,服务器开发好的服务怎么测试呢?其实很简单,postman可以很...

  • socket 模拟http请求

  • 使用Spring的RestTemplate发送Http请求

    使用Spring的RestTemplate发送Http请求 1,Spring的RestTemplate 1.1 基...

  • iOS 真机抓包方式

    Charles 优点 通过设置 http(s) 代理请求方式抓到请求,操作简单 可以模拟慢速,完全满足抓 http...

  • spring cloud gateway 2 深入了解 - fi

    简述 spring cloud gateway 路由过滤器修改传入的HTTP请求或传出的HTTP响应 spring...

网友评论

      本文标题:Spring模拟HTTP请求

      本文链接:https://www.haomeiwen.com/subject/jpubmctx.html