Search code examples
javaandroidandroid-studio

How to use HttpURLConnection in an Android app?


I have a problem in my Android app.
I use a login portal generated by an activity Login Activity, and I want to send username and password to my web API. So I created a java class who use HttpURLConnection for contacting my API. This class was tested (with Netbeans) and everything work perfectly !
But when I call my function who connecting at the API in my Android app, nothing, any request is send. I added Internet permission in androidManifest, always nothing

androidManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ben.myapp">
    <!-- Autorisation -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
.....
</manifest>

My java class :

public static String verifyLoginAndGetData (String userMail, String userPassword) throws IOException  {
           URL urlGetRequest = new URL("http://my.api.com/index?param1...");
           // HTTP Connexion
            HttpURLConnection apiConnexion = (HttpURLConnection) urlGetRequest.openConnection();
            // Method
            apiConnexion.setRequestMethod("GET");

            try {
                // Response code
                int responseCode = apiConnexion.getResponseCode();

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // Read the response
                    BufferedReader in = new BufferedReader(new InputStreamReader(apiConnexion.getInputStream()));
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    // Return response
                    return response.toString();

                } else {
                    return "false";
                }

            } finally {
                apiConnexion.disconnect();
            }

        } catch (Exception e){
            Log.i("Exception", e.toString());
            return "false";
        }

Where I call this function :

public class LoginDataSource {
     public Result<LoggedInUser> login(String username, String password) {
          String resultAPI = my_class.verifyLoginAndGetData(username, password);
     }
}

variables username and password are not empty.

what am I supposed to use ? Or what i should do ?
Thank you for helping me :)
BenjaminFB


Solution

  • Yes it work !!
    I did what @code-demon told me to do :
    Add at the Manifest

    android:usesCleartextTraffic="true"
    

    And use thred but I couldn't get any value back from API response, so I did research and came across it: stackoverflow post.
    Finally I developed that :

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<String> callable = new Callable<String>() {
          @Override
          public String call() throws IOException {
                // Call my API get function
                return verifyLoginAndGetData(username, password);
          }
    };
    Future<String> future = executor.submit(callable);
    executor.shutdown();
    // Get in String, the API response
    String resultAPI = future.get();