SpringBoot外调的几种方式 || http、https配置

一、简介

在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求,针对这一需求目前存在着三种解决方案,下面将对这三种方案进行整理和说明。

二、Spring-Boot项目中访问外部接口

2.1 方案一 采用原生的Http请求
在代码中采用原生的http请求,代码参考如下:

@RequestMapping("/doPostGetJson")
public String doPostGetJson() throws ParseException {
   //此处将要发送的数据转换为json格式字符串
   String jsonText = "{id:1}";
   JSONObject json = (JSONObject) JSONObject.parse(jsonText);
   JSONObject sr = this.doPost(json);
   System.out.println("返回参数:" + sr);
   return sr.toString();
}

public static JSONObject doPost(JSONObject date) {
   HttpClient client = HttpClients.createDefault();
   // 要调用的接口方法
   String url = "http://192.168.1.101:8080/getJson";
   HttpPost post = new HttpPost(url);
   JSONObject jsonObject = null;
   try {
      StringEntity s = new StringEntity(date.toString());
      s.setContentEncoding("UTF-8");
      s.setContentType("application/json");
      post.setEntity(s);
      post.addHeader("content-type", "text/xml");
      HttpResponse res = client.execute(post);
      String response1 = EntityUtils.toString(res.getEntity());
      System.out.println(response1);
      if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
         String result = EntityUtils.toString(res.getEntity());// 返回json格式:
         jsonObject = JSONObject.parseObject(result);
      }
   } catch (Exception e) {
      throw new RuntimeException(e);
   }
   return jsonObject;
}

2.2 方案二 采用Feign进行消费
1、在maven项目中添加依赖

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-feign</artifactId>
      <version>1.2.2.RELEASE</version>
</dependency>

2、编写接口,放置在service层

@FeignClient(url = "${decisionEngine.url}",name="engine")
public interface DecisionEngineService {
  @RequestMapping(value="/decision/person",method= RequestMethod.POST)
  public JSONObject getEngineMesasge(@RequestParam("uid") String uid,@RequestParam("productCode") String productCode);

}

这里的decisionEngine.url 是配置在properties中的 是ip地址和端口号
decisionEngine.url=http://10.2.1.148:3333
/decision/person 是接口名字

3、在Java的启动类上加上@EnableFeignClients


@EnableFeignClients //参见此处
@EnableDiscoveryClient
@SpringBootApplication
@EnableResourceServer
public class Application   implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
    @Autowired
    private AppMetricsExporter appMetricsExporter;

    @Autowired
    private AddMonitorUnitService addMonitorUnitService;

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }    
}

4、在代码中调用接口即可

@Autowired
    private DecisionEngineService decisionEngineService ;
    decisionEngineService.getEngineMesasge("uid" ,  "productCode");

2.3、方案三 采用RestTemplate方法
在Spring-Boot开发中,RestTemplate同样提供了对外访问的接口API,这里主要介绍Get和Post方法的使用。Get请求提供了两种方式的接口getForObject 和 getForEntity,getForEntity提供如下三种方法的实现。
Get请求之——getForEntity(Stringurl,Class responseType,Object…urlVariables)
该方法提供了三个参数,其中url为请求的地址,responseType为请求响应body的包装类型,urlVariables为url中的参数绑定,该方法的参考调用如下:

//http://USER-SERVICE/user?name={1}
getForEntity("http://USER-SERVICE/user?name={1}",String.class,"didi")

Get请求之——getForEntity(String url,Class responseType,Map urlVariables)
该方法提供的参数中urlVariables的参数类型使用了Map类型,因此在使用该方法进行参数绑定时需要在占位符中指定Map中参数的key值,该方法的参考调用如下:

// http://USER-SERVICE/user?name={name)
RestTemplate restTemplate=new RestTemplate();
Map<String,String> params=new HashMap<>();
params.put("name","dada");  //
ResponseEntity<String> responseEntity=restTemplate.getForEntity("http://USERSERVICE/user?name={name}",String.class,params);

Get请求之——getForEntity(URI url,Class responseType)
该方法使用URI对象来替代之前的url和urlVariables参数来指定访问地址和参数绑定。URI是JDK java.net包下的一个类,表示一个统一资源标识符(Uniform Resource Identifier)引用。参考如下:

RestTemplate restTemplate=new RestTemplate();
UriComponents uriComponents=UriComponentsBuilder.fromUriString(
"http://USER-SERVICE/user?name={name}")
.build()
.expand("dodo")
.encode();
URI uri=uriComponents.toUri();
ResponseEntity<String> responseEntity=restTemplate.getForEntity(uri,String.class).getBody();

Get请求之——getForObject
getForObject方法可以理解为对getForEntity的进一步封装,它通过HttpMessageConverterExtractor对HTTP的请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容。getForObject方法有如下:

getForObject(String url,Class responseType,Object...urlVariables)
getForObject(String url,Class responseType,Map urlVariables)
getForObject(URI url,Class responseType)

Post请求提供有三种方法,postForEntity、postForObject和postForLocation。其中每种方法都存在三种方法,postForEntity方法使用如下:

RestTemplate restTemplate=new RestTemplate();
User user=newUser("didi",30);
ResponseEntity<String> responseEntity=restTemplate.postForEntity("http://USER-SERVICE/user",user,String.class); //提交的body内容为user对象,请求的返回的body类型为String
String body=responseEntity.getBody();

postForEntity存在如下三种方法的重载

postForEntity(String url,Object request,Class responseType,Object... uriVariables)
postForEntity(String url,Object request,Class responseType,Map uriVariables)
postForEntity(URI url,Object request,Class responseType)

postForEntity中的其它参数和getForEntity的参数大体相同在此不做介绍。

原文链接:https://blog.csdn.net/polo2044/article/details/85002282

====================SpringBoot接口Http协议开发实战  =============================

1、SpringBoot2.xHTTP请求配置讲解

    简介:SpringBoot2.xHTTP请求注解讲解和简化注解配置技巧

    1、@RestController and @RequestMapping是springMVC的注解,不是springboot特有的    
    2、@RestController = @Controller+@ResponseBody    
    3、@SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan
        localhost:8080


2、开发接口必备工具之PostMan接口调试工具介绍和使用
    简介:模拟Http接口测试工具PostMan安装和讲解

        1、接口调试工具安装和基本使用
        2、下载地址:https://www.getpostman.com/

    

3、SpringBoot基础HTTP接口GET请求实战
    简介:讲解springboot接口,http的get请求,各个注解使用
        1、GET请求
            1、单一参数@RequestMapping(path = "/{id}", method = RequestMethod.GET)
                1) public String getUser(@PathVariable String id ) {}
                
                2)@RequestMapping(path = "/{depid}/{userid}", method = RequestMethod.GET) 可以同时指定多个提交方法
                getUser(@PathVariable("depid") String departmentID,@PathVariable("userid") String userid)

                3)一个顶俩
                @GetMapping = @RequestMapping(method = RequestMethod.GET)
                @PostMapping = @RequestMapping(method = RequestMethod.POST)
                @PutMapping = @RequestMapping(method = RequestMethod.PUT)
                @DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)

                4)@RequestParam(value = "name", required = true)
                    可以设置默认值,比如分页 

                4)@RequestBody 请求体映射实体类
                    需要指定http头为 content-type为application/json charset=utf-8

                5)@RequestHeader 请求头,比如鉴权
                    @RequestHeader("access_token") String accessToken

                6)HttpServletRequest request自动注入获取参数


            
4、SpringBoot基础HTTP接口POST,PUT,DELETE请求实战
    简介:讲解http请求post,put, delete提交方式
           GET请求:一般是查询
            Post请求:一般是提交
            PUT请求:一般是更新
            DELETE请求:一般是删除
            表单验证或者登陆请求的时候可以用:
            //params的类型是map类型
            @PostMapping("/v1/login")
            public Object login(String id,String pwd){
                param.clear();
                param.put("id",id);
                param.put("pwd",pwd);
                return params;
            }
            上述的方法就可以拿到登陆的密码和用户,这样就可以和数据库的密码和用户进行对比。


5、常用json框架介绍和Jackson返回结果处理
    简介:介绍常用json框架和注解的使用,自定义返回json结构和格式

    1、常用框架 阿里 fastjson,谷歌gson等
        JavaBean序列化为Json,性能:Jackson > FastJson > Gson > Json-lib 同个结构
        测试方法:循环序列化百万次,次数达到一定才可以看出差别
        Jackson、FastJson、Gson类库各有优点,各有自己的专长
        空间换时间,时间换空间

    2、jackson处理相关自动
        指定字段不返回(比如密码不应该返回给前端,故用这个注解来注释不让密码进行序列化后的显示):@JsonIgnore
        指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
        空字段不返回:@JsonInclude(Include.NON_NUll)
        指定别名:@JsonProperty(@JsonProperty("account")尽可能用别名,为了不暴露数据库的字段,防止黑客的攻击)


6、SpringBoot2.x目录文件结构讲解
     简介:讲解SpringBoot目录文件结构和官方推荐的目录规范

     1、目录讲解
         src/main/java:存放代码
         src/main/resources
             static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
             templates:存放静态页面jsp,html,tpl
             config:存放配置文件,application.properties
             resources:

     2、引入依赖 Thymeleaf
         <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        注意:如果不引人这个依赖包,html文件应该放在默认加载文件夹里面,
        比如resources、static、public这个几个文件夹,才可以访问

     3、同个文件的加载顺序,静态资源文件
     Spring Boot 默认会挨个从
     META/resources > resources > static > public  里面找是否存在相应的资源,如果有则直接返回。

     4、默认配置    
         1)官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content

         2)spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 

     5、静态资源文件存储在CDN


7、SpringBoot2.x文件上传实战
    简介:讲解HTML页面文件上传和后端处理实战
        1、讲解springboot文件上传 MultipartFile file,源自SpringMVC
                        
            1)静态页面直接访问:localhost:8080/index.html
                注意点:
                    如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面
            2)MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
            
            访问路径 http://localhost:8080/images/39020dbb-9253-41b9-8ff9-403309ff3f19.jpeg

        

8、jar包方式运行web项目的文件上传和访问处理(核心知识)
    简介:讲解SpingBoot2.x使用 java -jar运行方式的图片上传和访问处理

    1、文件大小配置,启动类里面配置
        
            @Bean  
            public MultipartConfigElement multipartConfigElement() {  
                MultipartConfigFactory factory = new MultipartConfigFactory();  
                //单个文件最大  
                factory.setMaxFileSize("10240KB"); //KB,MB  
                /// 设置总上传数据总大小  
                factory.setMaxRequestSize("1024000KB");  
                return factory.createMultipartConfig();  
            }  

    2、打包成jar包,需要增加maven依赖
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        如果没加相关依赖,执行maven打包,运行后会报错:no main manifest attribute, in XXX.jar

        GUI:反编译工具,作用就是用于把class文件转换成java文件

    3、文件上传和访问需要指定磁盘路径
        application.properties中增加下面配置
            1) web.images-path=/Users/jack/Desktop
            2) spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path} 

    4、文件服务器:fastdfs,阿里云oss,nginx搭建一个简单的文件服务器
————————————————
原文链接:https://blog.csdn.net/u012429555/article/details/81276261

SpringBoot配置HTTPS,并实现HTTP访问自动转HTTPS访问

1.使用jdk自带的 keytools 创建证书

打开cmd窗口,输入如下命令

keytool -genkey -alias tomcat -keyalg RSA -keystore ./server.keystore 

按照提示进行操作

输入密钥库口令:123456
再次输入新口令:123456
您的名字与姓氏是什么?
  [Unknown]:  kaibowang
您的组织单位名称是什么?
  [Unknown]:  yuxuelian
您的组织名称是什么?
  [Unknown]:  yuxuelian
您所在的城市或区域名称是什么?
  [Unknown]:  chengdu
您所在的省/市/自治区名称是什么?
  [Unknown]:  chengdushi
该单位的双字母国家/地区代码是什么?
  [Unknown]:  china
CN=kaibowang, OU=yuxuelian, O=yuxuelian, L=chengdu, ST=chengdushi, C=china是否正确?
  [否]:  y

输入 <tomcat> 的密钥口令
        (如果和密钥库口令相同, 按回车):
再次输入新口令:

Warning:
JKS 密钥库使用专用格式。建议使用 "keytool -importkeystore -srckeystore C:UsersAdministrator.keystore -destkeystore C:UsersAdministrator.keystore -deststoretype pkcs12" 迁移到行业标准格式 PKCS12。

创建完成后,可在用户根目录查看生成的keystore文件

2.新建springboot项目,将上一步生成的keystone文件复制到项目的根目录,在application.properties添加如下配置

server.port=443
server.ssl.key-store=server.keystore
server.ssl.key-alias=tomcat
server.ssl.enabled=true
server.ssl.key-store-password=123456
server.ssl.key-store-type=JKS
说明一下

这里将服务器端口号设置成443端口,即https的默认访问端口,那么在进行https访问的时候可以不带端口号直接访问,如果端口被占用使用

netstat -ano

查看哪个进程号占用了端口,使用

tasklist|findstr (查看到的进程号)
# simple
C:UsersAdministrator>tasklist|findstr 3664
vmware-hostd.exe              3664 Services                   0      5,040 K

打开任务管理器,杀死占用进程,或打开对应的应用程序的设置,关闭监听
至此 https配置完毕 访问 https://localhost 查看是否配置成功

3.http访问自动转https访问

向spring容器中注入两个Bean,代码如下

    @Bean
    public Connector connector(){
        Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(80);
        connector.setSecure(false);
        connector.setRedirectPort(443);
        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
        TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint=new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection=new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }

首先 这里需要使用 TomcatServletWebServerFactory 这个类,网上清一色的都是使用 EmbeddedServletContainerFactory 这个类.
在新版本的SpringBoot中,我发现已近找不到这个类了,几经周转,翻阅源码,才找到这个类,这也是我为什么写这篇文章的初衷.
其次在这里设置http的监听端口为80端口,http默认端口,这样在访问的时候也可以不用带上端口号.
完成以上配置后,我们访问 http://localhost 即可自动跳转为 https://localhost

原文链接:https://www.jianshu.com/p/8d4aba3b972d

SpringBoot Web Https 配置

 

不管是游戏服务器开发,还是其它服务开发,越来越多的平台都要求服务端必须支持https的访问。以增加安全性。比如目前火热的小程序,要求服务端必须支持https,苹果商店也有说http请求要修改为https。所以https将会是游戏服务器的普遍需求。

一,证书生成

   证书可以自己使用jdk生成进行测试。但是在正常使用的时候,需要去第三方机构购买,网上也有免费的。不过有效期有限制。具体获取证书的方法这里不再详细说明了。一般拿到证书之后会得到这几个文件:

   cert.pem chain.pem   fullchain.pem  privkey.pem

二,将pem文件转化为keystore文件

如果使用nginx跳转的话,上面的证书文件可以直接使用,但是在tomcat中,证书的配置文件格式必须是.keystore的文件。所以需要做一下转化。

1、生成pkcs12格式的密钥文件:

$ openssl pkcs12 -export -in cert.pem -inkey privkey.pem -out my.pk12 -name mykey

(注:此过程中需要输入密码:123456)

2、生成keystore:

$ keytool -importkeystore -deststorepass 123456 -destkeypass 123456 -destkeystore my.keystore -srckeystore my.pk12 -srcstoretype PKCS12 -srcstorepass 123456 -alias shkey

成功之后会获得my.keystore文件。

三,在Spring boot web中配置https

首先是在application.properties中添加配置

1
2
3
4
5
server.port= 8446
 
server.ssl.key-store=/user/cert/my.keystore
 
server.ssl.key-store-password=123456

  

这样配置之后,启动服务,就可以https访问了。

四,同时支持http和https访问

1,http请求不跳转成https访问

这种方式是http请求单独走一个端口,https请求单独走一个端口。但是spring boot 的appplication.properties只能配置一个端口,这就需要我们手动再添加一个Connector了。

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
@Configuration
 
public class TomcatConfig {
 
@Bean
 
public EmbeddedServletContainerFactory servletContainerFactory(){
 
TomcatEmbeddedServletContainerFactory tomcatConfig = new TomcatEmbeddedServletContainerFactory();
 
tomcatConfig.addAdditionalTomcatConnectors(this.newHttpConnector());
 
return tomcatConfig;
 
}
 
private Connector newHttpConnector() {
 
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
 
connector.setScheme("http");
 
connector.setPort(8080);
 
connector.setSecure(false);
 
return connector;
 
}
 
}

  

这样普通 的http请求,可以访问8080端口了。

2,将http请求强制跳转到https

有时候我们的一些旧业务是使用的http,但是新业务以及将来的框架都必须强制使用https,那就需要做一下跳转,把收到的http请求强制跳转到https上面。

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
@Configuration
 
public class TomcatConfig {
 
@Bean
 
public EmbeddedServletContainerFactory servletContainerFactory(){
 
TomcatEmbeddedServletContainerFactory tomcatConfig = new TomcatEmbeddedServletContainerFactory(){
 
@Override
 
protected void postProcessContext(Context context) {
 
SecurityConstraint securityConstraint = new SecurityConstraint();
 
securityConstraint.setUserConstraint("CONFIDENTIAL");
 
SecurityCollection collection = new SecurityCollection();
 
// 这里不知道为什么,只能配置以/*结尾的path。这样配置表示全部请求使用安全模式,必须走https
 
collection.addPattern("/*");
 
//另外还可以配置哪些请求必须走https,这表示以/home/开头的请求必须走https
 
collection.addPattern("/home/*");
 
securityConstraint.addCollection(collection);
 
context.addConstraint(securityConstraint);
 
}
 
};
 
tomcatConfig.addAdditionalTomcatConnectors(this.newHttpConnector());
 
return tomcatConfig;
 
}
 
private Connector newHttpConnector() {
 
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
 
connector.setScheme("http");
 
connector.setPort(8080);
 
connector.setSecure(false);
 
// 如果只需要支持https访问,这里把收到的http请求跳转到https的端口
 
connector.setRedirectPort(8446);
 
return connector;
 
}
 
}

 

以上跳转也可以使用nginx实现。如果有什么问题可以评论留言或加QQ群:66728073交流

原文链接:https://www.cnblogs.com/wgslucky/p/9092128.html

原文地址:https://www.cnblogs.com/hanwuxing/p/11671430.html