标签:type jar success 代码 exec llb cli syn exe
特性
支持同步阻塞调用和具有回调的异步调用。
OkHttp支持Android 2.3及以上版本。 对于JDK,最低要求是1.7。
Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。
项目中使用EventBus:
S1.添加jar包或依赖
compile ‘com.squareup.okhttp3:okhttp:3.8.0‘
compile ‘com.squareup.okio:okio:1.13.0‘
S2.创建POST/GET请求:
S3.代码混淆
-dontwarn okio.**
-dontwarn javax.annotation.Nullable
-dontwarn javax.annotation.ParametersAreNonnullByDefault
OKHTTP主要方法:
// 创建请求
MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
.post(RequestBody.create(MEDIA_TYPE, json))
.url(url)
.build();
// 创建响应
Response response = client.newCall(request).execute(); // sync
Response response = client.newCall(request).enqueue(new Callback() { // async
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
// 获取结果
if (response.isSuccessful()) {
response.body().string();
}
// 超时设置
// 提交JSON数据示例
public static void postJsonExamAsync() {
String url = "http:localhost:8080/login/commitUserInfo";
String postJson = "{}";
RequestBody body = RequestBody.create(MEDIA_TYPE, postJson);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
参考文档:
Android OkHttp完全解析 是时候来了解OkHttp了
标签:type jar success 代码 exec llb cli syn exe
原文地址:http://www.cnblogs.com/zhen-android/p/6943112.html