Web服务不适用于Android Retrofit,但适用于Postman和Swift / iOS,获取401 Unauthorized

时间:2017-02-21 18:49:37

标签: android ios retrofit postman okhttp

简要介绍'技术内容'
使用Retrofit并不陌生,但遇到了这种奇怪的行为,我很难理解和修复, 我有两个网络服务,在Postman和iOS中都可以正常工作,但只有一个在Retrofit而不是其他工作, 在我的辩护中,我可以说我得到(未经授权)回复,这意味着我能够击中服务器并获得结果 在API开发人员的辩护中,他说它适用于Postman和其他设备,因此不是服务问题

如果有任何Retrofit专家告诉我为了得到这个错误,我背后可能会做什么改造?

技术STUFF
在谈论服务类型时,它包含 授权承载令牌 作为标题,每6个小时到期并且根本不包含参数(因此它应该很简单,对吧?)和一个简单的网址 http://hashchuna.nn-assets.com/api/locations
不幸的是,标题令牌无法与有效密钥共享,因为它在任何人都可以尝试之前就已过期,但无论如何它仍然是授权承载3d44626a55dbb024725984e0d37868336fd7e48a

我做了什么
我正在使用okhttp拦截添加授权标头来请求使用 addHeader / header 方法,url中没有空格cos没有参数 Getting 401 unauthorized error in retrofit?
Java: Android: Retrofit - using Call but, Response{code = 401,message=unauthorized}
https://github.com/square/retrofit/issues/1290
但他们没有帮助

警告
现在要记住这个棘手的部分,过期的令牌必须给出401错误,这是预期的,但问题是即使对于新创建的令牌我得到401,这是我的核心问题

LOG

D/OkHttp: --> GET http://hashchuna.nn-assets.com/api/locations http/1.1
D/OkHttp: Authorization: Bearer 7c0d53de006b6de931f7d8747b22442354cecef9
D/OkHttp: --> END GET
D/OkHttp: <-- 401 Unauthorized http://hashchuna.nn-assets.com/api/locations (773ms)
D/OkHttp: Date: Mon, 20 Feb 2017 10:44:11 GMT
D/OkHttp: Server: Apache
D/OkHttp: X-Powered-By: PHP/7.0.15
D/OkHttp: Access-Control-Allow-Origin: *
D/OkHttp: Access-Control-Allow-Credentials: true
D/OkHttp: Access-Control-Max-Age: 1000
D/OkHttp: Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding
D/OkHttp: Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
D/OkHttp: Expires: Thu, 19 Nov 1981 08:52:00 GMT
D/OkHttp: Cache-Control: no-store, no-cache, must-revalidate
D/OkHttp: Pragma: no-cache
D/OkHttp: Set-Cookie: PHPSESSID=u477o8g0q387t92hms4nhc14n1; path=/
D/OkHttp: Vary: Authorization
D/OkHttp: X-Powered-By: PleskLin
D/OkHttp: Keep-Alive: timeout=5
D/OkHttp: Connection: Keep-Alive
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Content-Type: application/json;charset=utf-8
D/OkHttp: <-- END HTTP

CODE
拦截

Request request = chain
                        .request()
                        .newBuilder()
                        //.header("Authorization","Bearer "+ SharedPrefsUtils.getSPinstance().getAccessToken(context))
                        .addHeader("Authorization","Bearer 1ed6b7c1839e02bbf7a1b4a8dbca84d23127c68e")
                        //.addHeader("cache-control", "no-cache")
                        //.cacheControl(CacheControl.FORCE_NETWORK)
                        .build();

改造实例

private Api getApiInstance(Context context) {
        HttpLoggingInterceptor logInter = new HttpLoggingInterceptor();
        logInter.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient mIntercepter = new OkHttpClient.Builder()
                .addInterceptor(new RequestResponseInterseptor(context))
                .addInterceptor(logInter)
                .build();

        Retrofit retrofitInstance = new Retrofit.Builder()
                //.addConverterFactory(new NullOnEmptyConverterFactory())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .client(mIntercepter)
                .build();
        return retrofitInstance.create(Api.class);
    }

4 个答案:

答案 0 :(得分:4)

我认为您正在覆盖其他标题Retrofit正在为您添加,导致您的API不关心您的Authorization标头。下面的代码会在现有标题中添加标题,而不是覆盖它们。

    OkHttpClient mIntercepter = new OkHttpClient.Builder()
            ...
            .addInterceptor(new Interceptor() {
                 @Override 
                 public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer " + "1ed6b7c1839e02bbf7a1b4a8dbca84d23127c68e").build();
                        return chain.proceed(request);
            })
            ...
            .build();

这些标题的格式 正确,密钥应为Authorization,值应为Bearer 1ed6b7c1839e02bbf7a1b4a8dbca84d23127c68e(在您的情况下)。

答案 1 :(得分:3)

401 Unauthorized http://www.stackoverflow.com/api/login?email=test@test.com&password=123456
Date: Fri, 07 Apr 2017 11:23:28 GMT
Server: Apache/2.4.25 (Amazon) PHP/5.6.29
X-Powered-By: PHP/5.6.29
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Content-Length: 41
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json
{"msg":"Invalid Credentials"}

我遇到的问题就是无法获取错误消息。

当服务器抛出错误如401或其他错误时,我们从服务器获取null body。但您可以在errorBody

中收到来自服务器的错误消息
String response = response.errorBody().string()

答案 2 :(得分:1)

在我的情况下,遗憾的是,@ Ujju的解决方案中没有列出任何建议(即没有&#34; Cookie&#34;标题和CookieJar已应用)。唯一帮助我的是用addInterceptor取代addNetworkInterceptor,一切都开始奏效。

答案 3 :(得分:0)

我也面临这个问题。 请求不仅可以在POSTMAN中正常工作,而且可以在CURl中正常工作。 花了很多时间我找到了解决方案。

登录服务示例:

@FormUrlEncoded
@POST("authentication/login")
fun login(
    @Field("login") login: String,
    @Field("password") password: String
): Single<Void>

提供okhttp客户端:

private fun provideOkHttpClient(): OkHttpClient {

   val cookieManager = CookieManager()
   cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)

   val client = OkHttpClient.Builder()
      .cookieJar(JavaNetCookieJar(cookieManager))
      .addNetworkInterceptor(provideRequestInterceptor())
      .addNetworkInterceptor(provideLoggingInterceptor())
      .protocols(Arrays.asList(Protocol.HTTP_1_1))
      .build()

   return client
}

启用JavaNetCookieJar:

implementation "com.squareup.okhttp3:okhttp-urlconnection:$okHttpVersion"

提供授权:

private fun provideRequestInterceptor() = Interceptor {
    val builder = it.request().newBuilder().url(it.request().url())

    val tokenStr = BuildConfig.SONAR_TOKEN
    builder.addHeader("Authorization", "Basic "+ getBase64String(tokenStr+":"))

    it.proceed(builder.build())
}

private fun getBase64String(value: String): String {
    return Base64.encodeToString(value.toByteArray(charset("UTF-8")), Base64.NO_WRAP)
}