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();
}
}