一.接口
public interface HttpListener { void onFinish(String reponse); void onError(Exception e); }
二.OkHttpUtil
public class OkHttpUtil { public static void AsyncGet(String url, final HttpListener listener){ OkHttpClient http = new OkHttpClient(); final Request request = new Request.Builder() .url(url) .build(); Call call = http.newCall(request); call.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()); } }); } }
三.调用
OkHttpUtil.AsyncGet("http://www.baidu.com", new HttpListener() { @Override public void onFinish(String reponse) { Log.e("log", reponse); } @Override public void onError(Exception e) { e.printStackTrace(); } });
时间: 2024-10-23 18:38:04