栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

安卓前端连接springboot后端

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

安卓前端连接springboot后端

安卓前端连接springboot后端

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

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

    请先在AndroidManifest.xml文件中添加网络允许设置

    public class HttpUtils {
        
    
        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;
            }
        }
    }
    

    将传来的数据转化为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中
    }
    

    应用举例

    springboot的Controller层接口

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

    @RequestMapping("/post_main")
    @ResponseBody
    public List getAllPost(HttpSession session, ModelMap map) {
        List 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_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";//此处改为自己的路径

        
        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);


    }
}

END

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/756633.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号