How to Do Http Authentication in Android

How to do HTTP authentication in android?

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the java.net APIs, like so:

Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myuser","mypass".toCharArray());
}});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));

HTTP Get Android with Basic Auth

Maybe you can try something like this:

StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("YOUR WEBSITE HERE");

// Add authorization header
httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));

// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

As for writing a JSONObject, check out this code snippet:

public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "Jack Hack");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Hacker");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}

Basic Authentication Android API 20


Its worked for me.

Authenticator.setDefault(new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx","xxx1234".toCharArray());
}});

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(Integer.parseInt(context.getResources().getString(R.string.connection_timeout)));
connection.setUseCaches(false);
connection.connect();
HttpURLConnection httpConnection = connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
}

Login to a website with HTTP Basic Authentication from Android app

To access the web site you have to add the Authorization header.

First you have to concatenate and encode with base64 your credentials:

string credentials = username + ":" + password;
string credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");

then you add this header to your httpClient:

httpGet.setHeader("Authorization", "Basic "+credBase64);

Feel free to ask if you need more help.

basic authentication with http post params android

This is how to do it:

public String callServiceHttpPost(String userName, String password, String type)
{

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(WEBSERVICE + type);

String responseBody = "";

HttpResponse response = null;

try {

String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(userName + ":" + password).getBytes(),
Base64.NO_WRAP);


httppost.setHeader("Authorization", base64EncodedCredentials);

httppost.setHeader(HTTP.CONTENT_TYPE,"application/json");

JSONObject obj = new JSONObject();

obj.put("day", String.valueOf(2));
obj.put("emailId", "userTest@gmail.com");
obj.put("month", String.valueOf(5));
obj.put("year", String.valueOf(2013));


httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

// Execute HTTP Post Request
response = httpclient.execute(httppost);

if (response.getStatusLine().getStatusCode() == 200) {
Log.d("response ok", "ok response :/");
} else {
Log.d("response not ok", "Something went wrong :/");
}

responseBody = EntityUtils.toString(response.getEntity());

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}

return responseBody;
}

Retrofit and OkHttp basic authentication

Find the Solution

1.Write a Interceptor class

import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BasicAuthInterceptor implements Interceptor {

private String credentials;

public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}

@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}

}

2.Finally, add the interceptor to an OkHttp client

OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.build();

Basic Authentication Login in Android

In the next step you probably want to download the content from your website and process it in the app.
First of all, your app needs the permission Internet. Add the following line to your manifest file below the application tag:

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

Your website requires http authentication. To do this, you need to include your username and password in the headers of your request.
However, Android does not allow syncronous network traffic. Therefore we download the content from the website in the background and can then update the user interface via a callback. You can add my class DownloadContent to your project:

import android.os.AsyncTask;
import android.util.Base64;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import javax.net.ssl.HttpsURLConnection;

public class DownloadContent extends AsyncTask<String, Void, String> {
private final Callback callback;
private final String username, password;

private DownloadContent(@NonNull String username, @NonNull String password, @NonNull Callback callback) {
this.callback = callback;
this.username = username;
this.password = password;
}

public static void run(@NonNull String username, @NonNull String password, @NonNull Callback callback) {
DownloadContent loader = new DownloadContent(username, password, callback);
// runs doInBackground asynchronous
loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

@Override
protected String doInBackground(String... strings) {
try {
String credentials = username + ":" + password;
URL url = new URL ("https://vertretungsplanbbscux.000webhostapp.com/auth/index.html");
// encode to 64 encoded string (necessary for authorization header)
String base64 = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
// perform a post request
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// append encoded username and password as authorization header
connection.setRequestProperty ("Authorization", "Basic " + base64);
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader (new InputStreamReader(stream));
String inputLine;
StringBuilder response = new StringBuilder();
// read html of website
while ((inputLine = reader.readLine()) != null)
response.append(inputLine);
reader.close();
return response.toString();
} catch(Exception e) {
e.printStackTrace();
}
// return null if an error has occurred
return null;
}

@Override
protected void onPostExecute(@Nullable String content) {
// called after doInBackground has finished, synchronous again
if (content == null) {
callback.onNotLoaded();
} else {
callback.onLoaded(content);
}
}

public interface Callback {
void onLoaded(String content);
void onNotLoaded();
}
}

Here is how you can access the content:

DownloadContent.run("fost19", "12345", new DownloadContent.Callback() {
@Override
public void onLoaded(String content) {
Log.d("DownloadContent", content);
//TODO display content in user interface
}

@Override
public void onNotLoaded() {
Log.d("DownloadContent", "could not fetch content from website");
// TODO show error message
}
});

I hope that I could help you with your substitution plan app.

Edit1: You should only use a secure connection (https). So instead of using your .tk address, I used the actual secure address from your website.

Android OkHttp with Basic Authentication

Try using OkAuthenticator:

client.setAuthenticator(new OkAuthenticator() {
@Override public Credential authenticate(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
return Credential.basic("scott", "tiger");
}

@Override public Credential authenticateProxy(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
return null;
}
});

UPDATE:

Renamed to Authenticator



Related Topics



Leave a reply



Submit