当以主机ip为目标时,Ionic/Angular应用程序http请求无法使用Android emulator/real Android设备连接到Spring REST API
当我以实际主机地址192.168为目标时,我无法执行从Ionic应用程序到Spring API的任何http请求。。。。在我的Chrome浏览器中使用localhost可以很好地工作,在我的虚拟设备中使用Android emulator gateway 10.0.2.2也可以。但是,只要我使用我的主机ip,只有Chrome浏览器才能发送请求。我还确保我的真实设备与主机位于同一网络中,并且它实际上能够通过浏览器访问SpringAPI。不幸的是,如果我尝试在应用程序中发送http请求,我会收到一条非常空洞的错误消息:当以主机ip为目标时,Ionic/Angular应用程序http请求无法使用Android emulator/real Android设备连接到Spring REST API,spring,http,ionic-framework,networking,Spring,Http,Ionic Framework,Networking,当我以实际主机地址192.168为目标时,我无法执行从Ionic应用程序到Spring API的任何http请求。。。。在我的Chrome浏览器中使用localhost可以很好地工作,在我的虚拟设备中使用Android emulator gateway 10.0.2.2也可以。但是,只要我使用我的主机ip,只有Chrome浏览器才能发送请求。我还确保我的真实设备与主机位于同一网络中,并且它实际上能够通过浏览器访问SpringAPI。不幸的是,如果我尝试在应用程序中发送http请求,我会收到一条非
{
"headers":{
"normalizedNames":{},
"lazyUpdate":null,
"headers":{}
},
"status":0,
"statusText":"Unknown Error",
"url":"http://hostip:8080/authentication",
"ok":false,
"name":"HttpErrorResponse",
"message":"Http failure response for http://hostip:8080/authentication: 0 Unknown Error",
"error":{
"isTrusted":true
}
}
这是我的登录方法的外观:
login(email: string, password: string) {
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + base64string
}),
observe: 'response' as 'body',
withCredentials: true
};
return this.http.get(
'http://hostip:8080/authentication', httpOptions
);
}
在我的应用程序中的任何其他点上,我只是使用url和凭据调用http.get方法:true作为参数。
我还确保这些行包含在我的config.xml中:
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
我的Spring安全配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers(HttpMethod.GET).permitAll()
.antMatchers("/logout").permitAll()
.anyRequest().hasAnyRole("USER")
.and()
.httpBasic()
.and()
.logout();
}
}
我真的很感谢所有我能得到的帮助,我期待着你的回答。Android从版本9更改了它的http架构 要使其在Android上工作,请转到项目根文件夹 yourAppFolder>resources>android>xml> 网络安全配置.xml 将网络安全配置更改为blow code
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
你在检查哪个安卓版本?也检查一下:我在安卓8和10上检查过。哇,这就解决了!我找了几个小时,找不到解决办法。你真的救了我一天:-请随意写一个答案,这样我可以标记为解决方案,如果你想。
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>