1)需要打開網絡權限
先在AndroidManifest.xml文件manifest節點中添加如下配置:
<uses-permission android:name="android.permission.INTERNET"/>
2)json使用了
import net.sf.json.JSONObject;
需要引用幾個必須的包,不引用,編譯打包不報錯,但是程序會閃退!!!!
在app的libs下添加如下幾個JAR包,並且在app的build.gradle裏添加如下引用:
implementation files('libs/commons-beanutils-1.9.3.jar')
implementation files('libs/commons-collections.jar')
implementation files('libs/commons-lang-2.4.jar')
implementation files('libs/commons-logging-1.1.jar')
implementation files('libs/ezmorph-1.0.4.jar')
// implementation files('libs/fastjson-1.2.28.jar')
implementation files('libs/json-lib-2.3-jdk15.jar')
參考:https://blog.csdn.net/qq331059279/article/details/92832035
這個文章的資源裏提供了需要的JAR包。
2)targetSdk 27 以上版本,不允許使用http傳遞明文,需要使用https。
錯誤大概是這樣的:java.net.UnknownServiceException: CLEARTEXT communication ** not permitted by network security policy
針對這個問題,有以下四種解決方法:
(1)APP改用https請求。這個其實是最佳建議。
(2)targetSdkVersion 降到27以下。很多時候不行,telegram最新版本是要求27。不能用這個
(3)更改網絡安全配置(2種改法)
前面兩個方法容易理解和實現,具體說說第三種方法,更改網絡安全配置。
1.在res文件夾下創建一個xml文件夾,然後創建一個network_security_config.xml文件,文件內容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
2.接着,在AndroidManifest.xml文件下的application標籤增加以下屬性:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...
/>
完成,這個時候App就可以訪問網絡了。
3. 在AndroidManifest.xml配置文件的<application>標籤中直接插入(感謝junbs分享)
android:usesCleartextTraffic="true"
3)主線程不允許網絡連接,需要建立線程訪問或者,設置策略開啓。
方法一:想要忽略這些強制策略問題的話,可以在onCreate()方法裏面加上
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
他們說並在方法上加上@SuppressLint("NewApi"),不過我試了沒有加這句也管用。
方法二:啓動一個線程
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String result = (String) msg.getData().get("result");
String obj = (String) msg.obj;//
activity_main_btn1.setText("請求結果爲:"+result);
}
};
class WebServiceHandler implements Runnable{
@Override
public void run() {
Looper.prepare();
String result = sayHi("zxn");
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("result", result);
message.what = ANDROID_ACCESS_CXF_WEBSERVICES;//設置消息標示
message.obj = "zxn";
message. setData(bundle);//消息內容
handler.sendMessage(message);//發送消息
Looper.loop();
}
}