使用requestInterceptor改进基本身份验证

时间:2014-04-01 15:09:29

标签: java basic-authentication retrofit

我一直在尝试使用基本身份验证来使用retrofit和requestInterceptor,但我一直拒绝连接。我从https://github.com/square/retrofit的改造示例开始 链接到我开始使用的文件: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());
        }

    }

}

所以问题是这个。我有一台服务器在我的机器上本地运行,并且我已经使用CocoaRestClient成功执行了对它的请求,因此问题不在于服务器。这是错误的堆栈跟踪:

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

所以......连接被拒绝了......有什么建议吗?

2 个答案:

答案 0 :(得分:1)

对于仍在寻找答案的人(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);
        }
}

答案 1 :(得分:0)