0.请自行识别代码里的辅助性的提示信息代码,因时间关系不修改了。
有联网功能,要在项目的AndroidManifest.xml文件增加一行
<uses-permission android:name="android.permission.INTERNET" />
同时需要在request的地方先写权限代码
//如果要连接外网,必须在这里配置权限
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.INTERNET}, 1);
}
1.android的设计:一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。如果想在主线成操作,需要在activty的onCreate源码加上如下代码:
//解决主线程不能连接网络的问题 https://blog.csdn.net/llixiangjian/article/details/72910557
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
2. 在任何一个地方写http json request。注意,这里使用apache.http包,参考 http://hmkcode.com/android-send-json-data-to-server/ 添加依赖,file->project structure->选中app->dependencies-->右侧加号-->library-->输入 org.apache.http-->点击搜索-->搜到后添加。不一定是org.apche.http的原包,可能是封装包。
{
//测试http json request
InputStream is = null;
String result = "";
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
//1
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("http://120.27.1.1:8000/android/");
String json = "";
// 3. build jsonObject