安卓前端连接springboot后端

安卓前端连接springboot后端

本文仅记录安卓如何通过get请求获取springboot后端传来的json数据并解析,对springboot后端如何编写暂无涉及

  1. 准备好工具类HTTPUtils,此工具类用于连接后端的所要求的path路径,只需填入url路径即可,会返回后端传来的String字符串数据

    请先在AndroidManifest.xml文件中添加网络允许设置<uses-permission android:name="android.permission.INTERNET" />

    public class HttpUtils {
        /**
        * @Description: 封装好的http网络连接工具类
        * @Param: [urlStr] 为springboot所要求访问的RequestMapping网址
        * @return: java.lang.String
        * @Author: YAO
        * @Date: 2022/3/6
        */
    
        public static String gethttpresult(String urlStr) {
            try {
                URL url = new URL(urlStr);//获取url对象
                HttpURLConnection connect = (HttpURLConnection) url.openConnection();//url对象进行http连接
                InputStream input = connect.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(input));
                String line = null;
                System.out.println(connect.getResponseCode());
                StringBuffer sb = new StringBuffer();
                while ((line = in.readLine()) != null) {
                    sb.append(line);//逐行读取传来的String
                }
                return sb.toString();
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        }
    }
    
  2. 将传来的数据转化为JSON,并通过解析JSON来实现相当于读取数据库数据的目的

    String result = httpUtil.gethttpresult(url);//利用工具类获取网络连接
    JSONArray post_all = new JSONArray(result);//将返回的数据转换为JSON串格式
    //                        JSONArray post_all = result_json.getJSONArray("post_all");
    for (int i = 0; i < post_all.length(); i++) {
        post post_data = new post();//实例化post对象,用于存装从JSON解析出来的数据
    	JSONObject object = post_all.getJSONObject(i);
    	post_data.post_id = Integer.parseInt(object.getString("post_id"));
    	post_data.post_context = object.getString("post_context");
    	post_data.post_star = Integer.parseInt(object.getString("post_star"));
    	post_data.post_replay = Integer.parseInt(object.getString("post_replay"));
    	post_list.add(post_data);//将一个个装好JSON数据的对象加入到对象list中
    }
    
  3. 应用举例

    springboot的Controller层接口

@Controller
@RequestMapping("/post")
@ResponseBody
public class showPostController {
    @Autowired
    GetPostServiceImpl getPostService;

    @RequestMapping("/post_main")
    @ResponseBody
    public List<post> getAllPost(HttpSession session, ModelMap map) {
        List<post> post_all = new ArrayList<>();
        post post_data;
        int post_count = getPostService.getPostCount();
        for (int i = 1; i <= post_count; i++) {
            post_data = getPostService.getPost(i);
            post_all.add(post_data);
        }
        System.out.println(post_all);
        map.addAttribute("post_all", post_all);
        return post_all;
    }

可见路径为http://localhost:8080/post/post_main,返回的是从数据库中提取的List对象数组,其中post为自己设置的实例化对象,对应数据库中的一张表。

Activity的应用代码

public class HoleActivity extends AppCompatActivity {
    HoleAdapter mMyAdapter;
    RecyclerView mRecyclerView;
    List<post> post_list = new ArrayList<>();
    HttpUtils httpUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hole);

        String url = "http://yourip:8080/post/post_main";//此处改为自己的路径

        /**
         * @Description: 进入到RecyclerView页面后,向后端申请全部post数据
         * @Param: [savedInstanceState]
         * @return: void
         * @Author: YAO
         * @Date: 2022/3/6
         */
        new Thread() {
            @Override
            public void run() {
                String result = httpUtil.gethttpresult(url);//利用工具类获取网络连接
                System.out.println(result);
                if (result == null) {
                    Looper.prepare();
                    Toast.makeText(HoleActivity.this, "网络连接错误!", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                } else {
                    try {
                        JSONArray post_all = new JSONArray(result);//将返回的数据转换为JSON串格式
//                        JSONArray post_all = result_json.getJSONArray("post_all");
                        for (int i = 0; i < post_all.length(); i++) {
                            post post_data = new post();//实例化post对象,用于存装从JSON解析出来的数据
                            JSONObject object = post_all.getJSONObject(i);
                            post_data.post_id = Integer.parseInt(object.getString("post_id"));
                            post_data.post_context = object.getString("post_context");
                            post_data.post_star = Integer.parseInt(object.getString("post_star"));
                            post_data.post_replay = Integer.parseInt(object.getString("post_replay"));

                            post_list.add(post_data);//将一个个装好JSON数据的对象加入到对象list中
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                        System.out.println(e.toString());
                        Looper.prepare();
                        Toast.makeText(HoleActivity.this, "文件解析错误!", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }

            }
        }.start();

        //获取RecyclerView对象
        mRecyclerView = findViewById(R.id.hole_rv);


        //设置adapter
        mMyAdapter = new HoleAdapter(HoleActivity.this, post_list);
        mRecyclerView.setAdapter(mMyAdapter);

        //设置layoutManager
        LinearLayoutManager layoutManager = new LinearLayoutManager(HoleActivity.this);
        mRecyclerView.setLayoutManager(layoutManager);

        //设置Decoration分割线
        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        decoration.setDrawable(getResources().getDrawable(R.drawable.divider, null));
        mRecyclerView.addItemDecoration(decoration);


    }
}

项目源码链接:https://github.com/YaoTengqi/GreenLife

END

  • 7
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值