服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring远程调用HttpClient/RestTemplate的方法

Spring远程调用HttpClient/RestTemplate的方法

2021-08-20 11:23依旧ฅ=ฅ Java教程

这篇文章主要介绍了Spring远程调用HttpClient/RestTemplate的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、httpclient

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

       采用httpclient实现跨系统的接口调用。

介绍:

Spring远程调用HttpClient/RestTemplate的方法

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

现在也叫:httpcomponents

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

使用:

导入坐标

?
1
2
3
4
5
<dependency>
  <groupid>org.apache.httpcomponents</groupid>
  <artifactid>httpclient</artifactid>
  <version>4.4</version>
</dependency>
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//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://www.baidu.com/");
 
    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();
    }
 
  }
}
 
 
//2、使用httpclient发起带参数的get请求
public class dogetparam {
 
  public static void main(string[] args) throws exception {
    // 创建httpclient对象
    closeablehttpclient httpclient = httpclients.createdefault();
    // 创建uri对象,并且设置请求参数
    uri uri = new uribuilder("http://www.baidu.com/s").setparameter("wd", "java").build();
    
    // 创建http get请求
    httpget httpget = new httpget(uri);
 
    // httpget get = new httpget("http://www.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://www.oschina.net/");
    // 把自己伪装成浏览器。否则开源中国会拦截访问
    httppost.setheader("user-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://www.oschina.net/search");
 
    // 根据开源中国的请求需要,设置post请求参数
    list<namevaluepair> parameters = new arraylist<namevaluepair>(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开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多。

导入坐标

?
1
2
3
4
<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-web</artifactid>
</dependency>

创建resttemplate对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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<string> findbyid(@pathvariable integer id){
    //发起远程请求:通过resttemplate发起get请求
    responseentity<string> 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<string> savegoods(@requestbody goods goods){
    //通过resttemplate发起远程请求
    /**
     * 第一个参数:远程地址uri
     * 第二个参数:数据
     * 第三个参数:返回值类型
     */
    responseentity<string> 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<string> updategoods(@requestbody goods goods){
    resttemplate.put("http://localhost:8090/goods2",goods);
    return new responseentity<>("修改成功", httpstatus.ok);
  }
 
  @deletemapping("/{id}")
  public responseentity<string> deletebyid(@pathvariable integer id){
    resttemplate.delete("http://localhost:8090/goods2/"+id);
    return new responseentity<>("删除成功", httpstatus.ok);
  }
}

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

?
1
2
3
4
<dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-web</artifactid>
</dependency>

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

到此这篇关于spring远程调用httpclient/resttemplate的方法的文章就介绍到这了,更多相关spring远程调用httpclient/resttemplate内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_44065303/article/details/114392582

延伸 · 阅读

精彩推荐