個人專案---隨手記(一)
阿新 • • 發佈:2019-02-10
public class OkHttpUtil {
public static void sendHttpRequest(final String address,
final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request
.Builder()
.url(address)
.get()
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (listener != null) {
listener.onError(e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (listener != null) {
/**
* 不能用toString,否則返回的是地址字串
* */
listener.onFinish(response.body().string());
}
}
});
}
}).start();
}
}