如何从Android设备访问本地REST API?

编程入门 行业动态 更新时间:2024-10-12 03:25:42
本文介绍了如何从Android设备访问本地REST API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的计算机上本地运行有一个Spring REST api.我想使用此api进行android开发.

I have a spring REST api running locally on my computer. I would like to consume this api for android development.

这是我的获取请求:

public static String sendGet(final String url) { StringBuilder result = new StringBuilder(); HttpURLConnection urlConnection = null; try { String apiUrl = getAbsoluteUrl(url); // concatenate uri with base url eg: localhost:8080/ + uri URL requestUrl = new URL(apiUrl); urlConnection = (HttpURLConnection) requestUrl.openConnection(); urlConnection.connect(); // no connection is made InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } return result.toString(); }

我可以通过设备的浏览器访问我的api.但是,当我在内置apk中使用相同的URL发出请求时,没有建立连接.

I can access my api via my device's browser. However, when I use this same url within the built apk to make the request, no connection is made.

我的清单包括:

<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

旁注:

我正在通过USB将设备连接到运行rest api的笔记本电脑. 我正在使用通过调用ipconfig找到的WLAN IPv4地址.

I am connecting my device to my laptop running the rest api via usb. I am using the WLAN IPv4 address found by calling ipconfig.

任何朝着正确方向的提示将不胜感激-谢谢!

Any tips in the right direction would be much appreciated - thanks!

编辑以包括从我的笔记本电脑上运行的本地REST api输出的chrome浏览器(在android设备上)输出(返回默认来宾用户信息的GET请求):

Edit to include chrome browser (on android device) output from local REST api running on my laptop (A GET request to return default guest user information):

推荐答案

已解决,如果有人有兴趣:

SOLVED if anyone is interested:

我设法通过扩展原来的sendGet(final String url)所在的类来解决此问题,如下所示HttpClientUsage extends AsyncTask<String, Void, String>更多信息,并且可以在此处找到教程: AsyncTask教程

I managed to fix this issue by extending the class my original sendGet(final String url) was in as follows HttpClientUsage extends AsyncTask<String, Void, String> more information and a tutorial can be found here: AsyncTask tutorial

然后我必须在本地REST API上配置我的CORS设置,如下所示:

I then had to configure my CORS settings on my local REST API as follows:

cors: allowed-origins: "*" allowed-methods: GET, PUT, POST, DELETE, OPTIONS allowed-headers: "*" exposed-headers: allow-credentials: true max-age: 1800

非常感谢您的帮助.

更多推荐

如何从Android设备访问本地REST API?

本文发布于:2023-11-28 02:51:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设备   Android   API   REST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!