最佳网络编程实践二

HttpUtil.java


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by 王德强 on 2017/7/25.
 */

public class HttpUtil{
 public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request= new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
    }
}

我们在调用sendOhHttpRequest()方法的时候就可以这样写:

HttpUtil.sendOkHttpRequest("http://www.baidu.com",new okhttp3.Callback) throws IOException{
@Override
public void onResponse(Call call,Response response){
//得到服务器返回的具体内容
  String responseData = response.body().string();
}
@Override
public void onFailure(Call call,IOException e){
 //在这里对异常进行处理
}
}
posted @ 2017-07-25 10:31  Philtell  阅读(65)  评论(0编辑  收藏  举报