试试这个csdn怎么写,顺便记录下今天的感悟。今天在看okhttp3,对这个网络框架有了新的认识。
1、开篇
在项目module下的build.gradle添加okhttp3依赖
compile 'com.squareup.okhttp3:okhttp:3.11.0'
官方地址:git地址
1.1 OkHttp3同步get用法
/**
* 同步Get方法
*/
private void okHttp_synchronousGet() {
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "https://api.github.com/";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okhttp3.Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i(TAG, response.body().string());
} else {
Log.i(TAG, "okHttp is request error");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Request是okhttp3 的请求对象,Response是okhttp3中的响应。通过response.isSuccessful()判断请求是否成功。获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;string()适用于获取小数据信息,如果返回的数据超过1M,建议使用stream()获取返回的数据,因为string() 方法会将整个文档加载到内存中.
图片大小前面的=有个空格。。
1.2、okhttp3 异步 Get方法
有时候需要下载一份文件(比如网络图片),如果文件比较大,整个下载会比较耗时,通常我们会将耗时任务放到工作线程中,而使用okhttp3异步方法,不需要我们开启工作线程执行网络请求,返回的结果也在工作线程中;
/**
* 异步 Get方法
*/
private void okHttp_asynchronousGet(){
try {
Log.i(TAG,"main thread id is "+Thread.currentThread().getId());
String url = "你请求的地址";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
// 注:该回调是子线程,非主线程
Log.i(TAG,"callback thread id is "+Thread.currentThread().getId());
Log.i(TAG,response.body().string());
}
});
} catch (Exception e) {
e.printStackTrace();
}
注:Android 4.0 之后,要求网络请求必须在工作线程中运行,不再允许在主线程中运行。因此,如果使用 okhttp3 的同步Get方法,需要新起工作线程调用。
1.3、添加请求头
okhttp3添加请求头,需要在Request.Builder()使用.header(String key,String value)或者.addHeader(String key,String value);
使用.header(String key,String value),如果key已经存在,将会移除该key对应的value,然后将新value添加进来,即替换掉原来的value;
使用.addHeader(String key,String value),即使当前的可以已经存在值了,只会添加新value的值,并不会移除/替换原来的值。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}
2、post方法
2.1、Post 提交键值对
private void okHttp_postFromParameters() {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 请求完整url:http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
String url = "http://api.k780.com:88/";
OkHttpClient okHttpClient = new OkHttpClient();
String json = "{'app':'weather.future','weaid':'1','appkey':'10003'," +
"'sign':'b59bc3ef6191eb9f747dd4e83c99f2a4','format':'json'}";
RequestBody formBody = new FormBody.Builder().add("app", "weather.future")
.add("weaid", "1").add("appkey", "10003").add("sign",
"b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
okhttp3.Response response = okHttpClient.newCall(request).execute();
Log.i(TAG, response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
2.2、Post a String
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
2.3、post file
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File("README.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}