2. 权限
<读取外部存储>
<写入外部存储>
<网络权限>
<访问网络状态>
<访问无线网络状态>
设置结果回调监听,对请求结果进行统一处理
4Nohttp.流程图
添加依赖包,首先找到Gradle Scripts中找到build.gradle,必须选择(Module:app),找到以后将依赖包:compile 'com.yolanda.nohttp:nohttp:1.1.0' 粘贴到dependencies中
参照:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.yolanda.nohttp:nohttp:1.1.0'
testCompile 'junit:junit:4.12'
}
java布局:
Nohttp初始化需要一个Context,最好在
Application的
onCreate()中初始化,记得在
manifest.xml中注册
Application。
初始化:创建一个MyApplicatin类继承Application,实现onCreate()方法,然后进行初始化
public class MyApplication extends Application{
@Override
public void onCreate() {
//NoHttp默认初始化
NoHttp.initialize(this);
super.onCreate();
}
}
Java代码使用Nohttp的get和post的两种方式
提示:如果使用post请求,注意进行数据的add添加,上传数据
首先初始化控件:
public class MainActivity extends AppCompatActivity {
private TextView mMtv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMtv = (TextView) findViewById(R.id.tv);
}
get()方法:
get是从服务器上获取数据,如果这些数据是中文数据而且是非敏感数据,那么使用 get
public void btn_get(View view) {
//使用Nohttp进行网络访问的网址
String url = "http://www.baidu.com";
//1.创建一个队列
RequestQueue queue = NoHttp.newRequestQueue();
//2.创建消息请求,参数1 String字符串,传网址 参数2:指定请求的方式
//提示:(你们请求的数据是什么类型,就调用对象的方法,主要是中间的单词有区别)
Request request = NoHttp.createStringRequest(url, RequestMethod.GET);
//3.利用队列去添加消息队列 参数1:请求的标识 参数2:消息请求对象 参数3:请求的回调的监听
//请求可以并发,统一处理响应结果
queue.add(0, request, new OnResponseListener() {
//请求开始时回调的方法,一般做进度条对话框的加载
@Override
public void onStart(int what) {
}
//请求成功,回调的方法,代码直接运行到主线程
@Override
public void onSucceed(int what, Response response) {
//获取的响应结果,设置到TextView进行展示
String result = response.get();
mMtv.setText(result);
}
//网络请求失败的回调
@Override
public void onFailed(int what, Response response) {
Toast.makeText(MainActivity.this, "您的网络故障,请及时修复,在尝试", Toast.LENGTH_SHORT).show();
}
//网络请求成功,一般隐藏进度条对话框
@Override
public void onFinish(int what) {
}
});
}
post()方法;
post是向服务器传送数据,如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 post为好。
//根据点击事件,执行Nohttp的post方式
public void btn_post(View view) {
String postUrl = "http://192.168.3.107:8080/web/LoginServlet";
//1.创建一个队列
RequestQueue queue = NoHttp.newRequestQueue();
//2.创建消息请求 参数1:String字符串,传网址 参数2:请求方式
Request request = NoHttp.createStringRequest(postUrl, RequestMethod.POST);
//3.利用队列去添加消息请求
//使用request对象添加上传的对象添加键与值,post方式添加上传的数据
request.add("qq", "10000");
request.add("pwd", "abcde");
queue.add(1, request, new OnResponseListener() {
@Override
public void onStart(int what) {
}
@Override
public void onSucceed(int what, Response response) {
mMtv.setText(response.get());
}
@Override
public void onFailed(int what, Response response) {
Toast.makeText(MainActivity.this, "您的网络故障,请及时修复,在尝试", Toast.LENGTH_SHORT).show();
}
@Override
public void onFinish(int what) {
}
});
}
}