OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7
Set the JDK version
见:Configure Android Studio
A copy of the latest OpenJDK comes bundled with Android Studio 2.2 and higher, and this is the JDK version we recommend you use for your Android projects. To use the bundled JDK, proceed as follows:
- Open your project in Android Studio and select File > Project Structure in the menu bar.
- In the SDK Location page and under JDK location, check the Use embedded JDK checkbox.
- Click OK.
By default, the Java language version used to compile your project is based on your project's compileSdkVersion (because different versions of Android support different versions of Java). If necessary, you can override this default Java version by adding the following CompileOptions {} block to yourbuild.gradle file:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
}
}
For more information about where compileSdkVersion is defined, read about the module-level build file.
当compileSdkVersion>19时,SDK支持JDK1.7 ,所以只要gradle配置的compileSdkVersion>19即可
添加依赖
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.okio:okio:1.13.0'
}
添加网络权限
异步Get请求
private void asyncGet() {
mOkHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("https://www.baidu.com").get().build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "------" + response.body().string());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
异步Post请求
private void asyncPost() {
mOkHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("size", "10")
.build();
Request request = new Request.Builder()
.url("https://xxxxxxxx")
.post(requestBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "------" + response.body().string());
}
});
}
异步Post上传文件
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private void asyncPostFile() {
mOkHttpClient = new OkHttpClient();
File file = new File("/sdcard/abc.txt");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_MARKDOWN, file);
Request request = new Request.Builder()
.url("https://xxxxxxxx")
.post(requestBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "------" + response.body().string());
}
});
}
异步上传Multipart文件
public static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void asyncPostMultipart() {
mOkHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "hello_world")
.addFormDataPart("image", "hello.png", RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/hello.jpg")))
.build();
Request request = new Request.Builder()
.url("https://xxxxxxxx")
.post(requestBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "------" + response.body().string());
}
});
}
设置超时时间和缓存
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(getExternalCacheDir(), 10 * 1024 * 1024));
OkHttpClient okHttpClient = builder.build();
取消请求
call.cancle();
参考文章
Android网络编程(六)OkHttp3用法全解