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
2
Answers
Yes it work !!
I did what @code-demon told me to do :
Add at the Manifest
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 :
First of all have this run on a separate thread from the ui if not done already,for this id do this
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 http://www.google.com using get
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