Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrofit Basic auth with requestInterceptor

I've been trying to get basic authentication to work with retrofit and a requestInterceptor, but I keep getting connection refused. I started from the retrofit example at https://github.com/square/retrofit Link to file I started with: https://github.com/square/retrofit/blob/master/retrofit-samples/github-client/src/main/java/com/example/retrofit/GitHubClient.java

import java.util.List;

import javax.xml.bind.DatatypeConverter;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

public class Client {
    private static final String API_URL = "https://localhost:3000/v1";
    private static RestAdapter restAdapter = null;

    public RestAdapter getAdapter() {
        return restAdapter;
    }

    public static void init(final String username, final String password) {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Authorization", "Basic NTMzYWM5MmYxZTIxYmMwMDAwZWJlNTBlOmQ=");
                //getToken(username, password)
            }
        };

        restAdapter = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setRequestInterceptor(requestInterceptor)
            .build();

        //.setClient(new OkClient(okHttpClient))
    }

    public static void main(String... args) {
        // Create a REST adapter.
        init("533ac92f1e21bc0000ebe50e", "d"); //Currently not doing anything with these, supplying B64 coded value directly instead.

        // Create an instance of our GitHub API interface.
        IM2HDataStore m2hDataStore = restAdapter.create(IM2HDataStore.class);

        // Fetch and print a list of the samples.
        List<PositionSample> samples = m2hDataStore.positionSamples();
        for (PositionSample sample : samples) {
            System.out.println(sample.get_id());
        }

    }

}

So the problem is this. I have a server running locally on my machine and I've successfully performed requests to it with CocoaRestClient so the problem is not with the server. Here's a stack trace of the error:

Exception in thread "main" retrofit.RetrofitError: java.net.ConnectException: Connection refused
    at retrofit.RetrofitError.networkError(RetrofitError.java:27)
    at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:421)
    at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:284)
    at com.sun.proxy.$Proxy0.positionSamples(Unknown Source)
    at se.springworks.api.client.M2HClient.main(M2HClient.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
    at java.net.Socket.connect(Socket.java:527)
    at com.squareup.okhttp.internal.Platform.connectSocket(Platform.java:123)
    at com.squareup.okhttp.Connection.connect(Connection.java:98)
    at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:236)
    at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:180)
    at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:366)
    at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:319)
    at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:484)
    at com.squareup.okhttp.internal.http.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
    at com.squareup.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
    at retrofit.client.UrlConnectionClient.readResponse(UrlConnectionClient.java:71)
    at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:38)
    at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:358)
    ... 8 more

So... connection refused.. any advice?

like image 632
Coinhunter Avatar asked Nov 11 '22 10:11

Coinhunter


1 Answers

For someone still looking for answer (Retrofit 2.0.2)

 public class ServiceFactory {  
    public static ApiClient createService(String authToken, String userName, String password) {
            OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(
                            chain -> {
                                Request request = chain.request().newBuilder()
                                        .headers(getJsonHeader(authToken))
                                        .build();
                                return chain.proceed(request);
                            })
                    .authenticator(getBasicAuthenticator(userName, password))
                    .build();
            return getService(defaultHttpClient);
        }
        private static Headers getJsonHeader(String authToken) {
            Headers.Builder builder = new Headers.Builder();
            builder.add("Content-Type", "application/json");
            builder.add("Accept", "application/json");
            if (authToken != null && !authToken.isEmpty()) {
                builder.add("X-MY-Auth", authToken);
            }
            return builder.build();
        }
        private static Authenticator getBasicAuthenticator(final String userName, final String password) {
            return (route, response) -> {
                String credential = Credentials.basic(userName, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            };
        }
          private static ApiClient getService(OkHttpClient defaultHttpClient) {
            return new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(defaultHttpClient)
                    .build()
                    .create(ApiClient.class);
        }
}
like image 57
Fawad Badar Avatar answered Nov 14 '22 22:11

Fawad Badar