大家好,又见面了,我是你们的朋友全栈君。今天我们来聊聊Android中的OkHttpClient通信。
首先,我们来看一下OkHttpClient的用法。
用法1:自定义缓存
```java
OkHttpClient httpclient = new OkHttpClient.Builder()
.cache(new Cache(new File("cacheDirectory"), new Long(10 * 1024 * 1024)))
.build();
```
用法2:当出现缓存冲突时(常用)
```java
OkHttpClient httpclient = new OkHttpClient();
```
提交请求:
用法1:
```java
httpclient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
```
用法2:
```java
Response response = httpclient.newCall(request).execute();
```
接下来,我们来看一下Request类。
```java
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class OkHttpHeader1Java {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.header("User-Agent", "OkHttp Header1.java") //键值对,唯一
.addHeader("Accept", "application/json;q=0.5") //添加不覆盖,这时又两个“key”,值分别为"value2"、"value3"
.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "postBody")) //RequestBody内容可以很丰富,第二个参数可以是多种类型的字符集
.build();
System.out.println(request);
}
}
```
```java
public class RequestBodyExample {
public static void main(String[] args) {
// 用法1:使用匿名内部类创建RequestBody对象
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("text/x-markdown; charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Numbers
");
sink.writeUtf8("-------
");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s
", i, factor(i)));
}
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
};
}
}
```
重构后的代码如下:
```java
// 创建 MultipartBody.Builder 对象并设置请求类型为表单
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(Header, RequestBody) // 添加包含头和body的Part
.addFormDataPart("title", "Square Logo") // 表单中添加表单
.addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")));
// 构建 MultipartBody 对象
MultipartBody requestBody = builder.build();
// 配置请求类型
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
MediaType mediaType1 = MediaType.parse("image/png");
// 使用 HttpClient 发起请求
Response response;
if (useCallback) {
Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败的情况
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 处理请求成功的情况,response 为 Response 对象
}
};
httpclient.newCall(request).enqueue(callback);
} else {
response = httpclient.newCall(request).execute();
}
```
以下是重构后的代码,使用 Kotlin 语言:
```kotlin
val responseBody = response.body()
val responseString = responseBody.string()
val httpStatusCode = response.code()
val header1 = response.header("key1")
val header2 = response.header("key2")
val headers = response.headers("key1")
val networkResponse = response.networkResponse()
```
在这个版本中,我们使用了更具可读性的变量名,同时保留了原始代码的结构。