0

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

BenjaminFB
  • 43
  • 1
  • 8

2 Answers2

0

First of all have this run on a separate thread from the ui if not done already,for this id do this

new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.e("Download ",verifyLoginAndGetData("username","password"));
                    } catch (IOException e) {
                        Log.e("Exception ",""+e.getMessage());
                    }


                }
            }).start();
  • Next thing.am not sure about the api you are dealing with however id recommend using a network config file to allow cleartext traffic to your site if it uses cleartext traffic and specify it on your application in manifest.

  • Another thing, remember the internet permission on your manifest

Other than that,for me this works with the google url www.google.com using get

  public static String verifyLoginAndGetData (String userMail, String userPassword) throws IOException {
    URL urlGetRequest = new URL("http://www.google.com");
    // 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();
            String inputLine = null;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // Return response
            return response.toString();

        } else {
            return "false";
        }

    } finally {
        Log.e("Disconnection", "e.toString()");
        apiConnexion.disconnect();
    }


}

To return data to another class or to the activity thread, yo can use a handler or interface .below is how i would use an interface

  interface data_inter{
    void onDataReceived(String data);
}
data_inter inter=new data_inter() {
    @Override
    public void onDataReceived(String data) {
        Log.e("Downloaded: ",data);
        Toast.makeText(cntx,"Downloaded: "+data,Toast.LENGTH_LONG).show();
        ((EditText)findViewById(R.id.focuser)).setText("Downloaded: "+data);
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    cntx=this;
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String responce=verifyLoginAndGetData("","");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        inter.onDataReceived(responce);
                    }
                });

            } catch (IOException e) {
                Log.e("Exception ",""+e.getMessage());
            }


        }
    }).start();}
Code Demon
  • 1,256
  • 1
  • 9
  • 15
  • Oh Thanks its work ! I add `android:usesCleartextTraffic="true"` at from manifest and the request call in the thread sent perfectly. But now, how can I return API response values of the thread ? – BenjaminFB Aug 09 '21 at 10:16
0

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();
BenjaminFB
  • 43
  • 1
  • 8