okhttp是一个十分优秀的网络框架,特点网络上搜索便有,就不再赘述,这一篇看okhttp怎么使用
okhttp源码下载地址是:https://github.com/square/okhttp
本文示例下载地址:https://github.com/cmyeyi/NetFramework.git
目前的版本是3.11.0 (2018年8月13日)
使用起来非常简单
1、引入依赖库
在build.gradle中加入
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
如下图:在加入成功后,会在External Libraries下看到okhttp和okio两个jar。
2、实践get方法
/**
* 测试okhttp的get方法
*/
private void testOkhttpGet() {
String url = "http://api.k780.com/?app=weather.history";
okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
OkHttpClient okHttpClient = new OkHttpClient();
final Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = Message.obtain();
message.what = 0;
message.obj = e.getMessage();
mHandler.sendMessage(message);
Log.d(TAG, "onFailure: " + message.obj.toString());
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Message message = Message.obtain();
message.what = 1;
message.obj = response.body().string();//string不能调用两次 被调用一次就关闭了,这里调用两次会报异常
mHandler.sendMessage(message);
Log.d(TAG, "response: " + message.obj.toString());
}
});
}
结果仅贴出部分:
response: {"success":"0","msgid":"1000555","msg":"Parameter appkey or sign invalid."}
3、实践post方法
/**
* 测试okhttp的post方法
*/
private void testOkhttpPost() {
String url = "http://api.k780.com/?app=weather.history";//
// &weaid=1&date=2018-08-13&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("weaid", "1")
.add("date", "2018-08-13")
.add("appkey", "10003")
.add("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4")
.add("format", "json")
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = Message.obtain();
message.what = 0;
message.obj = e.getMessage();
mHandler.sendMessage(message);
Log.d(TAG, "response: " + message.obj.toString());
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Message message = Message.obtain();
message.what = 1;
message.obj = response.body().string();//string不能调用两次 被调用一次就关闭了,这里调用两次会报异常
mHandler.sendMessage(message);
Log.d(TAG, "response: " + message.obj.toString());
}
});
}
請求结果:(格式化了一下)
"success": "1",
"result": [
{
"weaid": "1",
"week": "星期一",
"cityno": "beijing",
"citynm": "北京",
"cityid": "101010100",
"uptime": "2018-08-13 00:30:00",
"temperature": "25℃",
"humidity": "98%",
"aqi": "53",
"weather": "阴",
"weather_icon": "http://api.k780.com/upload/weather/d/2.gif",
"wind": "西南风",
"winp": "1级",
"temp": "25",
"weatid": "3",
"windid": "16",
"winpid": "201",
"weather_iconid": "2"
},
{
"weaid": "1",
"week": "星期一",
"cityno": "beijing",
"citynm": "北京",
"cityid": "101010100",
"uptime": "2018-08-13 02:30:00",
"temperature": "25℃",
"humidity": "98%",
"aqi": "42",
"weather": "阵雨",
"weather_icon": "http://api.k780.com/upload/weather/d/3.gif",
"wind": "风",
"winp": "0级",
"temp": "25",
"weatid": "4",
"windid": "423",
"winpid": "207",
"weather_iconid": "3"
}
]
}
4、json格式个post请求
/**
* 测试同步okhttp的post方法,在使用的時候我們必须另起线程
*/
private void testOkhttpPostJson() {
String url = "http://api.k780.com/?app=weather.history";//
String json = "{\"format\":\"json\",\"weaid\":1,\"date\":\"2018-08-13\",\"appkey\":\"10003\",\"sign\":\"b59bc3ef6191eb9f747dd4e83c99f2a4\"}";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request request = new Request.Builder().post(body).url(url).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = Message.obtain();
message.what = 0;
message.obj = e.getMessage();
mHandler.sendMessage(message);
Log.d(TAG, "response: " + message.obj.toString());
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Message message = Message.obtain();
message.what = 1;
message.obj = response.body().string();//string不能调用两次 被调用一次就关闭了,这里调用两次会报异常
mHandler.sendMessage(message);
Log.d(TAG, "response: " + message.obj.toString());
}
});
}
请求结果:
response: {"success":"0","msgid":"1000555","msg":"Parameter appkey or sign invalid."}
5、另外还有另外一种使用get、post请求的方式,如下面代码,注意这种方式需要另起线程调用
/**
* 测试同步okhttp的get方法,在使用的時候我們必须另起线程
*/
private String testOkhttpGetSynchronized() throws IOException {
String url = "http://api.k780.com/?app=weather.history";
okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
OkHttpClient okHttpClient = new OkHttpClient();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
/**
* 测试同步okhttp的post方法,在使用的時候我們必须另起线程
*/
private String testOkhttpPostSynchronized() throws IOException {
String url = "http://api.k780.com/?app=weather.history";//
// &weaid=1&date=2018-08-13&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
RequestBody body = new FormBody.Builder()
.add("weaid", "1")
.add("date", "2018-08-13")
.add("appkey", "10003")
.add("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4")
.add("format", "json")
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(body)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
另起线程调用,否则报错:
new Thread(new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
try {
String result = testOkhttpGetSynchronized();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
try {
String result = testOkhttpPostSynchronized();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();