Wednesday, 1 July 2015

AndroidServiceClient with Authentication

I'm currently researching ServiceStack as a replacement to my own services for handling REST between Android and Windows.

I've got the client (Android) working using loopj's AsyncHttpClient. But I was looking for a more native library. Initially I was using Jsonserviceclient but decided on the AndroidServiceClient. The problem I had was setting up basic authentication on the connection. After a few hours of reading (which AndroidServiceClient extends). It transpired I have to implement my own request ConnectionFilter and set uo the request headers in the void exec(HttpURLConnection urlConnection) method.

After creating code I got the error "cannot set request property after connection is made".
Seems I needed to tweak the code to suppress this error.

package com.jjoplc.pod.Views;

import android.util.Base64;
import net.servicestack.client.ConnectionFilter;

 * Created by norm on 01/07/2015.
public class CustomRequestFilter implements ConnectionFilter {

    private String password = "";
    private String username = "";

    static  boolean done = false;
    public void exec(HttpURLConnection urlConnection) {
        if (done) {
            done = false;

        done = true;

        String credentials = username + ":" + password;
        final String basicAuth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
        urlConnection.setRequestProperty("Authorization", basicAuth);

    public void setUsername(String userName) {
        this.username = userName;

    public void setPassword(String passWord) {
        this.password = passWord;

Set up.

 _androidClient = new AndroidServiceClient("http://myservice:8088");
_requestFilter = new CustomRequestFilter();
_androidClient.RequestFilter = _requestFilter;

And Test.

androidClient.getAsync(new dto.Hello().setName("Normski"), new AsyncResult<dto.HelloResponse>() {
    public void success(dto.HelloResponse r) {

    public void error(Exception ex) {

No comments:

Post a comment