我的计算机上本地运行有一个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?
发布评论