1.首先导入依赖
implementation'com.squareup.okhttp3:okhttp:3.10.0'
2.新建一个class
//封装OkHttpUtils
public class OkHttpUtils {
public OkHttpUtils() {
}
public OkHttpUtils get(String path) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url(path)
.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 {
getData.Data(response.body().string());
}
});
return this;
}
//写一个接口
public interface GetData {
void Data(String s);
}
private GetData getData;
public void getDataLisener(GetData getData) {
this.getData = getData;
}
}
3.在Activity中调用
public class MainActivity extends AppCompatActivity {
private ListView listView;
private String path = "http://www.xieast.com/api/news/news.php?page=1";
private ArrayList<User.Data> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
listView = (ListView) findViewById(R.id.listview);
SearchView searchView = (SearchView) findViewById(R.id.searchView);
searchView.setQueryHint("请输入搜索内容");
searchView.setIconifiedByDefault(false);
OkHttpUtils okHttpUtils = new OkHttpUtils();
okHttpUtils.get(path).getDataLisener(new OkHttpUtils.GetData() {
@Override
public void Data(String s) {
list = new ArrayList<>();
Gson gson = new Gson();
User user = gson.fromJson(s, User.class);
ArrayList<User.Data> data = user.getData();
list.addAll(data);
Message message = Message.obtain();
message.obj = list;
handler.sendMessage(message);
}
});
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
MyAdapter myAdapter = new MyAdapter(MainActivity.this,list);
listView.setAdapter(myAdapter);
}
};
}