import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Okhttp {
public Okhttp(){
};
public Okhttp get(String wz){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url(wz)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String s = response.body().string();
Message message = new Message();
message.obj=s;
handler.sendMessage(message);
}
});
return this;
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String data = (String) msg.obj;
infor.success(data);
}
};
public interface Infor{
void success(String s);
}
Infor infor;
public void setInfor(Infor infor) {
this.infor = infor;
}
}
model层的使用
public class PicModel {
String path="http://v.juhe.cn/toutiao/index?type=&key=83a69c67e9272f816e42450ef0eb50ee";
public void getData(final CallBack callBack){
new Okhttp().get(path).setInfor(new Okhttp.Infor() {
@Override
public void success(String s) {
Gson gson=new Gson();
JsonBean jsonBean = gson.fromJson(s, JsonBean.class);
List<JsonBean.ResultBean.DataBean> data = jsonBean.getResult().getData();
if(data!=null){
callBack.onSuccess(data);
}else {
callBack.onFailed("数据为空");
}
}
});
};