赞
踩
原文转载: 深入解析OkHttp3.
OkHttp是一个精巧的网络请求库,有如下特性:
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
String url = "http://www.baidu.com";
OkHttpClient mHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okhttp3.Response response = null;
try {
response = mHttpClient.newCall(request).execute();
String json = response.body().string();
Log.d("okHttp",json);
} catch (IOException e) {
e.printStackTrace();
}
}
他说execute()是同步方法
异步使用enqueue()方法,需要回调函数
public void requestBlog() { String url = "http://write.blog.csdn.net/postlist/0/0/enabled/1"; OkHttpClient mHttpClient = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); mHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); Log.d("okHttp", json); } }); }
private void post(String url, String json) throws IOException { OkHttpClient client = new OkHttpClient(); //还有一种使用json的 //String json = "haha"; //RequestBody body = RequestBody.create(JSON, json); RequestBody formBody = new FormBody.Builder() .add("name", "liming") .add("school", "beida") .build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String str = response.body().string(); Log.i(TAG, str); } }); }
异步上传文件
OkHttpClient mOkHttpClient = new OkHttpClient();
File file = new File("/sdcard/demo.txt");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
异步上传字符串
OkHttpClient client = new OkHttpClient();
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * zhangfei\n"
+ " * guanyu\n"
+ " * liubei\n";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
提交分块请求
OkHttpClient client = new OkHttpClient(); // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image MultipartBody body = new MultipartBody.Builder("AaB03x") .setType(MultipartBody.FORM) .addPart( Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, "Square Logo")) .addPart( Headers.of("Content-Disposition", "form-data; name=\"image\""), RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build(); Request request = new Request.Builder() .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) .url("https://api.imgur.com/3/image") .post(body) .build();
响应缓存
int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(cacheDirectory, cacheSize); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.cache(cache); OkHttpClient client = builder.build(); Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String response1Body = response.body().string(); System.out.println("Response 1 response: " + response); System.out.println("Response 1 cache response: " + response.cacheResponse()); System.out.println("Response 1 network response: " + response.networkResponse()); } });
超时
private void ConfigureTimeouts() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); OkHttpClient client = builder.build(); client.newBuilder().connectTimeout(10, TimeUnit.SECONDS); client.newBuilder().readTimeout(10,TimeUnit.SECONDS); client.newBuilder().writeTimeout(10,TimeUnit.SECONDS); Request request = new Request.Builder() .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("Response completed: " + response); } }); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。