OkHTTP请求封装

OkHTTP请求封装

public class OkhttpUtils {

private final OkHttpClient okHttpClient ;
private final Handler handler ;

// 单例模式
private OkhttpUtils() {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout( 1000 , TimeUnit. SECONDS )
.readTimeout( 1000 , TimeUnit. SECONDS )
.writeTimeout( 1000 , TimeUnit. SECONDS )
.build();
handler = new Handler();

}

private static OkhttpUtils okhttpUtils = null ;

public static OkhttpUtils getOkhttpUtils() {
if ( okhttpUtils == null ) {
okhttpUtils = new OkhttpUtils();
}
return okhttpUtils ;
}

// 接口回调 json
public interface Fun1 {
void getResultJson(String String);
}

private Fun1 fun1 ;

public void getSuccessJson(String url, final Fun1 fun1) {
final Request request = new Request.Builder().url(url).build();

okHttpClient .newCall(request).enqueue( new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String s = response.body().string();
handler .post( new Runnable() {
@Override
public void run() {
fun1 .getResultJson( s );
}
});
}
});
}
}

你可能感兴趣的:(OkHTTP请求封装)