Android利用Get/Post方式异步请求Json数据,显示在ListView中

简单的网络数据请求

一、配置AndroidMainfest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.wangyanchuan.show_ison">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>
    </application>

</manifest>

如代码所示在application前添加<uses-permission android:name="android.permission.INTERNET"/>

二、在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<Info> infoList = new ArrayList<Info>();
    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<resultJsonArray.length();i++){
                        object=resultJsonArray.getJSONObject(i);

                        try {
                            //获取到json数据中的activity数组里的内容
                            String BookID = object.getString("BookID");
                            //获取到json数据中的activity数组里的内容
                            String FromUser=object.getString("FromUser");
                            Info bb=new Info(BookID, FromUser);

                            //ArrayList集合
                            infoList.add(bb);

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                    Message message1 = new Message();
                    message1.what = 1;
                    handler.sendMessage(message1);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }//[]结束

    //Handler运行在主线程中(UI线程中),  它与子线程可以通过Message对象来传递数据
    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    InfoAdapter adapter = new InfoAdapter(MainActivity.this, R.layout.info_item, infoList);
                    listView.setAdapter(adapter);
                    break;
            }
        }
    };

}

有几点事情要注意:

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<Info> 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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/info_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="TextView" />

    <TextView
        android:id="@+id/info_bookname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="TextView" />

</LinearLayout>

item布局

大约就是这样,我们一起进步!

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值