当前位置:网站首页 > 更多 > 编程开发 > 正文

[安卓] 利用okhttp3调用接口,用gson解析json数据

作者:CC下载站 日期:2020-09-24 00:00:00 浏览:72 分类:编程开发

开心,总算搞好了

调用接口获取所有用户信息,然后打印出来了。

MainActivity.java

packageink.cik.logininfoapp;

importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;

importandroidx.appcompat.app.AppCompatActivity;

importcom.google.gson.Gson;
importcom.google.gson.reflect.TypeToken;

importjava.io.IOException;
importjava.util.List;
importjava.util.Map;

importokhttp3.OkHttpClient;
importokhttp3.Request;
importokhttp3.Response;

publicclassMainActivityextendsAppCompatActivity{
privatefinalGsongson=newGson();

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Buttonbutton=(Button)findViewById(R.id.loginButton);
button.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
EditTextuserName=findViewById(R.id.userName);
EditTextpassWord=findViewById(R.id.passWord);
Toast.makeText(MainActivity.this,userName.toString(),Toast.LENGTH_SHORT).show();
verLogin();
}
});
}

privatevoidverLogin(){
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
OkHttpClientclient=newOkHttpClient();
Requestrequest=newRequest.Builder().url("https://api.565.ink/login/getAll?passwd=lanol666").build();
Responseresponse=client.newCall(request).execute();
Stringresponsedata=response.body().string();
Log.d("返回数据:",responsedata);
parseJson(responsedata);
}catch(IOExceptione){
e.printStackTrace();
}
}
}).start();
}

privatevoidparseJson(StringJsonData){
Gsongson=newGson();
List<userInfo>userInfoList=gson.fromJson(JsonData,newTypeToken<List<userInfo>>(){
}.getType());
for(userInfouserInfo:userInfoList){
Log.d("信息:",userInfo.getUserName());
}
}
}

userInfo.java

packageink.cik.logininfoapp;

publicclassuserInfo{
privateintid;
privateStringuserName;
privateStringpassWord;
privateStringnation;
privateintage;
privateStringtel;

publicintgetAge(){
returnage;
}

publicStringgetNation(){
returnnation;
}

publicintgetId(){
returnid;
}

publicStringgetPassWord(){
returnpassWord;
}

publicStringgetTel(){
returntel;
}

publicStringgetUserName(){
returnuserName;
}

publicvoidsetAge(intage){
this.age=age;
}

publicvoidsetId(intid){
this.id=id;
}

publicvoidsetNation(Stringnation){
this.nation=nation;
}

publicvoidsetPassWord(StringpassWord){
this.passWord=passWord;
}

publicvoidsetTel(Stringtel){
this.tel=tel;
}

publicvoidsetUserName(StringuserName){
this.userName=userName;
}
}


您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯