Basic username/password authentication for ksoap2 on Android

The built-in HttpTransportBasicAuth class provided by ksoap2 doesn’t seem to be part of the ksoap2 Android assembly. The following class (adapted from here) works fine for me.

import java.io.IOException;

import org.kobjects.base64.Base64;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.ServiceConnection;

public class HttpTransportBasicAuth extends HttpTransportSE {

  private String username;
  private String password;

  public HttpTransportBasicAuth(String url, String username, String password) {
    super(url);
    this.username = username;
    this.password = password;
  }

  @Override
  public ServiceConnection getServiceConnection() throws IOException {
    ServiceConnection serviceConnection = super.getServiceConnection();
    addBasicAuthentication(serviceConnection);
    return serviceConnection;
  }

  protected void addBasicAuthentication(ServiceConnection serviceConnection) 
      throws IOException {
    
    if (username != null && password != null) {
      StringBuffer buffer = new StringBuffer(username);
      buffer.append(':').append(password);
      byte[] bytes = buffer.toString().getBytes();
      buffer.setLength(0);
      buffer.append("Basic ");
      Base64.encode(bytes, 0, bytes.length, buffer);
      serviceConnection.setRequestProperty
        ("Authorization", buffer.toString());
    }
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s