Search code examples
react-nativehttprequest

React Native doesn't work Get request on local network


I'm new and haven't been able to solve the problem for several days now. There is a device on the local network (smart home) that I can turn on and off from the browser without problems using a get request (http://192.168.0.100/Power?Power=1). I’m writing an application for Android, everything works fine in React Native in the emulator, but after installing the app on a real phone, nothing works anymore. Please help me figure it out.

const test = () => {
    fetch('http://192.168.0.100/Power?Power=1', true)
  };
return (
     <TouchableOpacity
        onPress={() => test()}>
     </TouchableOpacity>
       )

Solution

  • I had a similar problem. Here is my solution:

    To switch a smarthome-device I can send a http-request with any browser: http://192.168.178.101/relay/0?turn=toggle But the attempt to write an app with android studio failed.

    I tried every library: the old apache, okhttp3, khttp, fuel and volley.

    Here a very short code snippet with volley. This works fine with an http-adress in www, but not in my home network:

    val requestQueue = Volley.newRequestQueue(this@MainActivity)
    url = "https://jsonplaceholder.typicode.com/users",
    val request = StringRequest(
        Request.Method.GET,
        url,
        {
            findViewById<TextView>(R.id.txtView1).text = it
        },
        { Log.d("error",it.toString())}
    )
    requestQueue.add(request)
    

    I added all thinkable permissions to androidmanifest.xml:

     <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION " />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    

    Astonishing, that the app works on my old smartphone with android 8!

    When comparing the Android versions I found this helpful thread: How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

    After insert this line to androidmanifest.xml it works !!

    android:usesCleartextTraffic="true"
    

    (Alternativ you can downgrade your sdk in gradle to targetSdk = 26, but that is only a emergency solution)