android 开发常见问题

1. 使用 okhttp 中 response 对象, 其中 response.body().string() 方法只能调用一次 不然就报错

1
FATAL EXCEPTION: OkHttp Dispatcher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class HttpUtils {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient client = new OkHttpClient();

public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}

public static void get(String url, HttpCallbackListener listener) {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(e);
}

@Override
public void onResponse(Call call, Response response) throws IOException {
listener.onFinish(response.body().string());
}
});
}

public static void post(String url, String json, HttpCallbackListener listener) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onError(e);
}

@Override
public void onResponse(Call call, Response response) throws IOException {
listener.onFinish(response.body().string());
}
});
}
}
```"