报错
No Network Security Config specified, using platform default
问题由来(原因)
大概是因为Android P(9.0)后,访问API接口需要加密…
解决办法
创建一个 network_security_config.xml,用来声明证书校验方式 network_security_config.xml 代码内容:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
在AndroidManifest.xml 引入network_security_config.xml,注意在AndroidManifest.xml中添加一行android:usesCleartextTraffic=“true”
<application
android:allowBackup="true"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
如果按照上述修改后还有报错
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
W/System.err: java.io.IOException: Cleartext HTTP traffic to XXX.XXX.XXX.XXX not permitted
解决方法
使用OkHttp请求API,这个问题困扰了我一天,发现换了一个方法就解决了,之前用的是HttpURLConnection,请求一直报错 OkHttp POST方法:
public static String okhttpPost(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
OkHttp GET方法:
public static void okhttpGet(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
Response response = call.execute();
String content = response.body().string();
System.out.println(content);
}
这里我调用POST方法,需要新建一个线程来调用,否则会报错,示例如下:
public void Check(View v) {
new Thread() {
@Override
public void run() {
GetApi getApi = new GetApi();
String url = getResources().getString(R.string.ipPort) +"/api/kgas/LoginUser";
JSONObject jsonDate = new JSONObject();
jsonDate.put("userName",userName.getText().toString());
jsonDate.put("passWord",Password.getText().toString());
try {
String callStr = getApi.okhttpPost(url, jsonDate.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
参考地址:Android OkHttp完全解析 是时候来了解OkHttp了
|