[英]Why Android emulator can't access API from online server?
I'm facing a problem which is my App can access API from iOS simulator
but it doesn't on Android emulator
. 我面临一个问题,那就是我的应用程序可以从
iOS simulator
访问API,但不能在Android emulator
。
I call the API like this : 我这样调用API:
async fetchData() {
let url = `http://1**.***.***.***/bla/bla`;
try{
let response = await fetch(url,{
headers: {
'x-application-id':'123',
'hashing': this.hashGenerator("message"),
'content-type': 'application/json'
},
method: "POST",
body: JSON.stringify({
"location":"city"
})
});
if(!response.ok){
throw new Error(response.status)
} else {
return await response.json();
}
} catch(error) {
this.setState({ loadingList: false });
}
}
Is it because I use http
instead of https
? 是否因为我使用
http
而不是https
?
I've been stuck since yesterday... 从昨天开始我就一直被困
For http
requests, certificate signing is required. 对于
http
请求,需要证书签名。 you can use the following code to trust all certificates for your app. 您可以使用以下代码信任您应用的所有证书。 As your app is using your server only, there should not be any security issue using this code.
由于您的应用仅使用服务器,因此使用此代码应该不会有任何安全问题。
public void trustAllCertificates() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] myTrustedAnchors = new X509Certificate[0];
return myTrustedAnchors;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (Exception e) {
}
}
Just call this function in your Application
class or in your main Activity
. 只需在
Application
类或主Activity
调用此函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.