每日学习

今天尝试将获取数据封装为一个类:

package com.example.bowenwang;

import android.os.Message;
import android.util.Log;

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 okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class getdata {
    List<Bean> list=new ArrayList<>();
    private OkHttpClient okHttpClient=new OkHttpClient();
    public List<Bean> get(int classify){
                new Thread(){
            @Override
            public void run() {
                super.run();
                list=new ArrayList<>();
                String url="http://39.103.196.146:8888/getNewsData/GetNewsDataServlet";
                try {
                    String result=getData(url,classify);
                    manageResponse(result);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        return list;
    }
    private String getData(String url,int classify) throws IOException {
        RequestBody responseBody=new FormBody.Builder()
                .add("classify", String.valueOf(classify+1))
                .build();
        Request request=new Request.Builder().post(responseBody).url(url).build();
        Response response=okHttpClient.newCall(request).execute();
        return response.body().string();
    }
    private void manageResponse(String result) throws JSONException {
        JSONArray jsonArray=new JSONArray(result);
        for(int i=0;i<jsonArray.length();i++)
        {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            String title=jsonObject.getString("title");
            String time=jsonObject.getString("time");
            String place=jsonObject.getString("place");
            String author=jsonObject.getString("author");
            String content=jsonObject.getString("content");
            String img=jsonObject.getString("img");
            Bean bean=new Bean();
            bean.setTitle(title);
            bean.setTime(time);
            bean.setPlace(place);
            bean.setContent(content);
            bean.setImg(img);
            list.add(bean);
        }
    }
}
作者:哦心有
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/haobox/p/14909331.html