当前位置:   article > 正文

安卓前端连接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;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
  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中
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

可见路径为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);


    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

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

END

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/264952
推荐阅读
相关标签
  

闽ICP备14008679号