retrofit Basic auth with requestInterceptor
我一直在尝试进行基本身份验证以与改造和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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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成功执行了对它的请求,因此问题不出在服务器上。这是错误的堆栈跟踪:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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.2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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); } } |
您可以使用java.net.Authenticator来配置基本身份验证。有关您的应用程序发送的每个请求的全局信息,请参见:
- http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html
- http://developer.android.com/reference/java/net/Authenticator.html#getPasswordAuthentication()