问题可能是因为在同一WiFi网络下使用HTTPS时,可能由于证书信任问题导致Android无法连接到Spring Boot后端。为了解决这个问题,可以尝试以下几个步骤:
1.在Spring Boot后端项目中配置自签名证书
@Configuration
public class SslConfiguration {
private final String KEY_STORE_PASSWORD = "password";
private final String KEY_STORE = "classpath:yourkeystore.jks";
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@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(initiateHttpConnector());
tomcat.addAdditionalTomcatConnectors(initiateHttpsConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
private Connector initiateHttpsConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
try {
File keystore = ResourceUtils.getFile(KEY_STORE);
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass(KEY_STORE_PASSWORD);
protocol.setKeyAlias("tomcat");
return connector;
} catch (FileNotFoundException ex) {
throw new IllegalStateException("Cannot load keystore", ex);
}
}
}
其中,KEY_STORE_PASSWORD、KEY_STORE和KEY_ALIAS可以根据实际情况进行修改。此配置类中会同时开启http和https两个连接器。
2.在Android应用中信任后端的自签名证书,并启用网络安全配置
在res目录下新建一个xml文件夹,在其中创建一个network_security_config.xml文件,内容如下: