1. Without a doubt, add dependencies
I am using this version
implementation 'com.squareup.okhttp3:okhttp:4.0.0'
2. Come to a client (okhttpclient)
OkHttpClient client = new OkHttpClient.Builder().build();
Three, a request (request)
Request request = new Request.Builder()
.get()
.url("http://dasai.sdvcst.edu.cn:8080/press/press/list?pageNum=1&pageSize=10")
.build();
Four, associate the client and request
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String string = response.body().string();
Message msg = Message.obtain();
msg.what=1;
msg.obj=string;
handler.sendMessage(msg);
}
});
5. Send information to the main thread through handlersend, so you need a handler
Six, process information in the handler
Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
String result = (String) msg.obj;
Gson gson = new Gson();
NewsBean bean = gson.fromJson(result, NewsBean.class);
adapter = new MyListAdapter(ListView.this, bean.getRows());
my_listview.setAdapter(adapter);
Log.e("wwwwwwwwwwwwwwwww", "handleMessage: \n"+result );
break;
}
}
};
Seven, a post request requires a requestbody, which requires two parameters, a json data, and a mediatype
OkHttpClient client = new OkHttpClient.Builder().build();
loginBean bean = new loginBean();
bean.setUsername("111");
bean.setPassword("111");
Gson gson = new Gson();
String toJson = gson.toJson(bean);
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, toJson);
Request request = new Request.Builder()
.post(body)
.url("http://dasai.sdvcst.edu.cn:8080/login")
.build();
PS: gson for analyzing data