Spring远程调用HttpClient/RestTemplate的方法

网友投稿 214 2022-11-01


Spring远程调用HttpClient/RestTemplate的方法

一、HttpClient

两个系统间如何互相访问?两个tomcat上的项目如何互相访问?

http://     采用HttpClient实现跨系统的接口调用。

介绍:

官网:http://hc.apache.org/index.html

现在也叫:HttpComponents

HttpClient可以发送get、post、put、delete、...等请求

使用:

导入坐标

org.apache.httpcomponents

httpclient

4.4

//1、使用HttpClient发起Get请求

public class DoGET {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象,相当于打开了浏览器

CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建HttpGet请求,相当于在浏览器输入地址

HttpGet httpGet = new HttpGet("http://baidu.com/");

CloseableHttpResponse response = null;

try {

// 执行请求,相当于敲完地址后按下回车。获取响应

response = httpclient.execute(httpGet);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

// 解析http://响应,获取数据

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

} finally {

if (response != null) {

// 关闭资源

response.close();

}

// 关闭浏览器

httpclient.close();

}

}

}

//2、使用HttpClient发起带参数的Get请求

public class DoGETParam {

public static void main(String[] args) throws ExceptionDxGcBE {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建URI对象,并且设置请求参数

URI uri = new URIBuilder("http://baidu.com/s").setParameter("wd", "java").build();

// 创建http GET请求

HttpGet httpGet = new HttpGet(uri);

// HttpGet get = new HttpGet("http://baidu.com/s?wd=java");

CloseableHttpResponse response = null;

try {

// 执行请求

response = httpclient.execute(httpGet);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

// 解析响应数据

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

} finally {

if (response != null) {

response.close();

}

httpclient.close();

}

}

}

//3、使用HttpClient发起POST请求

public class DoPOST {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求

HttpPost httpPost = new HttpPost("http://oschina.net/");

// 把自己伪装成浏览器。否则开源中国会拦截访问

httpPost.setHeader("UseDxGcBEr-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");

CloseableHttpResponse response = null;

try {

// 执行请求

response = httpclient.execute(httpPost);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

// 解析响应数据

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

} finally {

if (response != null) {

response.close();

}

// 关闭浏览器

httpclient.close();

}

}

}

//4、使用HttpClient发起带有参数的POST请求

public class DoPOSTParam {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求,访问开源中国

HttpPost httpPost = new HttpPost("http://oschina.net/search");

// 根据开源中国的请求需要,设置post请求参数

List parameters = new ArrayList(0);

parameters.add(new BasicNameValuePair("scope", "project"));

parameters.add(new BasicNameValuePair("q", "java"));

parameters.add(new BasicNameValuePair("fromerr", "8bDnUWwC"));

// 构造一个form表单式的实体

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);

// 将请求实体设置到httpPost对象中

httpPost.setEntity(formEntity);

CloseableHttpResponse response = null;

try {

// 执行请求

response = httpclient.execute(httpPost);

// 判断返回状态是否为200

if (response.getStatusLine().getStatusCode() == 200) {

// 解析响应体

String content = EntityUtils.toString(response.getEntity(), "UTF-8");

System.out.println(content);

}

} finally {

if (response != null) {

response.close();

}

// 关闭浏览器

httpclient.close();

}

}

}

二、RestTemplate

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法

HTTP开发是用apache的HttpClient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多。

导入坐标

org.springframework.boot

spring-boot-starter-web

创建RestTemplate对象

@Configuration//加上这个注解作用,可以被Spring扫描

public class RestTemplateConfig {

/**

* 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring

* @return

*/

@Bean

public RestTemplate restTemplate(){

RestTemplate restTemplate = new RestTemplate();

//主要解决中文乱码

restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

return restTemplate;

}

}

RestTempController

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController

@RequestMapping("/consumer")

public class ConsumerController {

// 从Spring的容器中获取restTemplate

@Resource

private RestTemplate restTemplate;

/**

* 通过Get请求,保存数据

*/

@GetMapping("/{id}")

public ResponseEntity findById(@PathVariable Integer id){

//发起远程请求:通过RestTemplate发起get请求

ResponseEntity entity = restTemplate.getForEntity("http://localhost:8090/goods2/1", String.class);

System.out.println("entity.getStatusCode():"+entity.getStatusCode());

System.out.println(entity.getBody());

return entity;

}

/**

* 通过Post请求,保存数据

*/

@PostMapping

public ResponseEntity saveGoods(@RequestBody Goods goods){

//通过RestTemplate发起远程请求

/**

* 第一个参数:远程地址URI

* 第二个参数:数据

* 第三个参数:返回值类型

*/

ResponseEntity entity = restTemplate.postForEntity("http://localhost:8090/goods2", goods, String.class);

System.out.println("entity.getStatusCode():"+entity.getStatusCode());

System.out.println(entity.getBody());

return entity;

}

@PutMapping

public ResponseEntity updateGoods(@RequestBody Goods goods){

restTemplate.put("http://localhost:8090/goods2",goods);

return new ResponseEntity<>("修改成功", HttpStatus.OK);

}

@DeleteMapping("/{id}")

public ResponseEntity deleteById(@PathVariable Integer id){

restTemplate.delete("http://localhost:8090/goods2/"+id);

return new ResponseEntity<>("删除成功", HttpStatus.OK);

}

}

只用maven不用springboot框架时只需要导入依赖到pom文件

org.springframework

spring-web

直接new RestTemplate()对象使用即可


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:WPF+MVVM数据绑定问题集锦
下一篇:怎么使用 nvm 控制 nodejs 版本切换?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~