一.接口

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();
            }
        });

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-03-31
  • 2021-07-06
  • 2021-05-24
猜你喜欢
  • 2021-07-07
  • 2021-09-21
  • 2021-09-30
  • 2021-07-13
  • 2021-06-25
  • 2021-06-01
  • 2022-12-23
相关资源
相似解决方案