一爽待、毫無疑問,添加依賴
我用的是這個版本
implementation 'com.squareup.okhttp3:okhttp:4.0.0'
二翩腐、來一個客戶端(okhttpclient)
OkHttpClient client = new OkHttpClient.Builder().build();
三堕伪、來一個請求(request)
Request request = new Request.Builder()
.get()
.url("http://dasai.sdvcst.edu.cn:8080/press/press/list?pageNum=1&pageSize=10")
.build();
四、關(guān)聯(lián)客戶端與請求
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);
}
});
五栗菜、通過handlersend將信息發(fā)到主線程欠雌,所以要一個handler
六、在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;
}
}
};
七疙筹、post請求則需要一個requestbody富俄,requestbody里面需要兩個參數(shù),一個json數(shù)據(jù)而咆,一個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:解析數(shù)據(jù)用的gson