How can I access my local REST api from my Android device?

I have apache spring REST running locally on my computer. I would like to use this api for Android development.

Here is my request for receipt:

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

I can access my api through the browser of my device. However, when I use the same URL inside the built-in apk to execute the request, the connection is not made.

My manifest includes:

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

Side notes:

I connect my device to a laptop using the rest of the api via usb. I am using the WLAN IP address found by calling ipconfig.

Any advice in the right direction would be greatly appreciated - thanks!

Chrome ( Android) REST api, ( GET ): enter image description here

+4
4

SOLVED, - :

, , sendGet(final String url) HttpClientUsage extends AsyncTask<String, Void, String>, : AsyncTask

CORS REST API :

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

, .

+1

ip: - ip (, )

  • type ipconfig
  • Ip

enter image description here

URL : http://192.168.240.2/index.html

+3

. Android-, 10.0.2.2 IP- -, REST API.

, Genymotion, Oracle Virtualbox, 10.0.3.2.

+2

Your holiday url should be something like this - http://localhost:8080/yourRest/restMethod.
Instead of localhost url, connect your mobile and local computer on the same network (Wi-Fi network). Get the IP address of the local computer , for example 192.168.1.X ... so now your final resting URL will behttp://192.168.1.X:8080/yourRest/restMethod

+1
source

Source: https://habr.com/ru/post/1664030/


All Articles