现在的android开发绝大多数都使用okhttp请求数据。
okhttp必须在安装完所有okhttp所需环境文件后才能过使用,分为okhttp.jar和okio.jar,下载地址为:"http://square.github.io/okhttp/"。
或者直接在AS的build.gradle的dependencies中加入
compile 'com.squareup.okhttp3:okhttp:3.5.0'
然后点击右上角的Sync Now导入,等待下载完毕即可。
等待完毕后即可开始网络请求,网络请求分为两种,get和post方法。
okhttp的get请求分为4步:
1.建立okhttp对象
OkHttpClient okhttpclient = new OkHttpClient();
2.构造request
Request.Builder buider = new Request.Builder();
Request request = buider.get().url("https://www.imooc.com/").build();
3.将request封装成Call
Call call = okhttpclient.newCall(request);
4.执行Call(异步 ps:此操作不能操作UI)
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
get操作完成。
okhttp的psot请求分为4步:
1.构造RequestBody
这里以构造一个json数据为例
MediaType JSON = MediaType.parse("application/json;charset=utf-8");
Map map = new HashMap<>();
map.put("test","test");
JSONObject jsonObject = new JSONObject(map);
RequestBody requestBody = RequestBody.create(JSON,jsonObject.toString());
2.建立okhttp对象
OkHttpClient okHttpClient = new OkHttpClient();
3.构造一个Request
Request request = new Request.Builder()
.post(requestBody)
.url("")
.build();
4.将Request封装为Call
Call call = okHttpClient.newCall(request);
5.执行Call
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//请求成功
}
});
这样子post操作就完成了。