Android利用Get/Post方式异步请求Json数据,显示在ListView中
16lz
2021-01-26
简单的网络数据请求
一、配置AndroidMainfest.xml文件
<?xml version="1.0" encoding="utf-8"?>
如代码所示在application前添加
二、在build.gradle的dependencies添加OKHTTP包
implementation 'com.squareup.okhttp3:okhttp:3.11.0'implementation 'com.squareup.okio:okio:2.1.0'
注意okio也是要添加的。
三、编写MainActivity.java文件
import android.annotation.SuppressLint;import android.nfc.Tag;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.ListView;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeUnit;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;/**演示OkHttp网络框架的使用 OkHttp是用于网络请求数据的一个网络框架工具*/public class MainActivity extends AppCompatActivity { public List infoList = new ArrayList(); public ListView listView; public JSONObject object; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /**get请求方式*/ public void net1(View view) { //创建网络处理的对象 infoList.clear(); listView = (ListView) findViewById(R.id.list_view); OkHttpClient client = new OkHttpClient.Builder() //设置读取数据的时间 .readTimeout(5, TimeUnit.SECONDS) //对象的创建 .build(); //创建一个网络请求的对象,如果没有写请求方式,默认的是get //在请求对象里面传入链接的URL地址 Request request = new Request.Builder() .url("http://***********").build(); //call就是我们可以执行的请求类 Call call = client.newCall(request); //异步方法,来执行任务的处理,一般都是使用异步方法执行的 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //失败 Log.e("TAG",Thread.currentThread().getName() + "结果 " + e.toString()); }//获取线程名称 @Override public void onResponse(Call call, Response response) throws IOException { //成功 //子线程 //main thread1 String date1=response.body().string(); jsonJXS(date1); } }); //同步方法,一般不用 /* try { Response execute = call.execute(); } catch (IOException e) { e.printStackTrace(); }*/ } /**post请求方式,请求网络数据 请求某接口的json数据*/ public void net2(View view) { //创建网络处理的对象 infoList.clear(); listView = (ListView) findViewById(R.id.list_view); OkHttpClient client = new OkHttpClient.Builder() .readTimeout(5, TimeUnit.SECONDS) .build(); //post请求来获得数据 //创建一个RequestBody,存放重要数据的键值对 RequestBody body = new FormBody.Builder() .add("账户", "密码").build(); //创建一个请求对象,传入URL地址和相关数据的键值对的对象 Request request = new Request.Builder() .url("http://**************") .post(body).build(); //创建一个能处理请求数据的操作类 Call call = client.newCall(request); //使用异步任务的模式请求数据 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("TAG","错误信息:" + e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { //Log.e("TAG",response.body().string()); String date=response.body().string(); jsonJX(date); } }); }//post 结束 private void jsonJX(String date) { //判断数据是空 /**解析并配置Json(psot方式根节点{})数据*/ if(date!=null){ try { //将字符串转换成jsonObject对象 JSONObject jsonObject = new JSONObject(date); try { //获取到json数据中的activity数组里的内容 String username = jsonObject.getString("UserName"); //获取到json数据中的activity数组里的内容 String bookname=jsonObject.getString("Nickname"); //存入aa Info aa=new Info(username, bookname); //ArrayList集合 infoList.add(aa); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //} Message message = new Message(); message.what = 1; handler.sendMessage(message); //} } catch (JSONException e) { e.printStackTrace(); } } }//{}结束 private void jsonJXS(String date) { //判断数据是空 /**get方法请求json数据(根节点【】)*/ if(date!=null){ try { //获取到json数据中里的activity数组内容 JSONArray resultJsonArray = new JSONArray(date); //遍历 for(int i=0;i
有几点事情要注意:
1.请求json数据是要用异步请求(net1),(net2)方法。
1.本例get请求json数据根节点为[],故在解析数据时(jsonJXS)方法,用JSONArray。
2.本例Post请求json数据根节点为{},故在解析数据(jsonJX)方法,用JSONObject。
四、编写ListView
public class Info { private String username; private String bookname; public Info(String username, String bookname) { this.username = username; this.bookname = bookname; } public String getusername() { return username; } public String getbookname() { return bookname; }}
Info类,即每个元组的数据
public class InfoAdapter extends ArrayAdapter{ private final int resourceId; public InfoAdapter(Context context, int textViewResourceId, List objects) { super(context, textViewResourceId, objects); resourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { Info info = (Info) getItem(position); // 获取当前项的实例 View view = LayoutInflater.from(getContext()).inflate(resourceId, null);//实例化一个对象 TextView username = (TextView) view.findViewById(R.id.info_username);//获取该布局内的视图 TextView bookname = (TextView) view.findViewById(R.id.info_bookname);//获取该布局内的视图 username.setText(info.getusername()); bookname.setText(info.getbookname()); return view; }}
线性表适配器
<?xml version="1.0" encoding="utf-8"?>
item布局
大约就是这样,我们一起进步!
更多相关文章
- 一句话锁定MySQL数据占用元凶
- Android底层字符传递给上层应用举例
- 解决小米平板 adb devices no permissions ,无法链接adb 问题
- Okhttp3+Rxjava+Retrofit2封装
- Android(安卓)Sqlite synchronous设置
- 安卓开发:学生信息管理小程序
- Android中使用SerialPort读取红外温度传感器数据
- android SharedPreferences保存应用数据
- Android(安卓)短信模块分析(八) MMS数据库表关系