实验结果:
服务器网址
http://112.124.22.238:8081/course_api/banner/query?type=1
step1
添加okhttp和Gson依赖(根据AS版本不同会有变化)
这里以28.0.0为例
implementation ‘com.squareup.okhttp:okhttp:2.7.5’
implementation ‘com.google.code.gson:gson:2.8.5’
step2
编写HttpGet或者HttpPost(其中之一即可)
HttpGet
private void requestImages(){
String url = "http://112.124.22.238:8081/course_api/banner/query?type=1";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
String json = response.body().string();
Log.i("HomeFragment", "json=" + json);
}
}
});
}
HttpPost
private void requestImages(){
String url = "http://112.124.22.238:8081/course_api/banner/query?";
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormEncodingBuilder()
.add("type","1")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
String json = response.body().string();
Log.i("HomeFragment", "json=" + json);
}
}
});
}
目前我们已经能够取得服务器上的json串了,使用时可以对其进行解析封装
这里提供一种方法,使用Gson解析
step1
编写一个BaseBean.java文件
package com.diabin.minda.bean;
import java.io.Serializable;
public class BaseBean implements Serializable {
protected long id;
public long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
}
step2
根据json串里的数据字段再编写一个Banner.java文件(实际上就是进行json数据的封装)
package com.diabin.minda.bean;
public class Banner extends BaseBean {
private String name;
private String imgUrl;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
step3
//声明Gson
private Gson mGson = new Gson();
//声明一个List来接收获得的JSon字符串
private List<Banner> mBanner;
step4
在HttpGet或者HttpPost的 if (response.isSuccessful())判断下添加以下代码
//尖括号内写入转换的类型,这里是一个List,并且是Banner的泛型
Type type = new TypeToken<List<Banner>>(){}.getType();
//进行Json到Gson的转换
mBanner = mGson.fromJson(json,type);
到这里大家应该知道怎么用了吧。。。。。
好吧,还是讲完吧。。。。。
step5
使用增强型for循环取出封装在List里的mBanner
if (mBanner != null){
//使用for循环取出mBanner中的Json数据
for (Banner banner : mBanner){
这里面就可以banner .get某某某即可,想用到什么地方就用到什么地方
}
}
以上如有疏漏请指正