Fast-android-networking: AddHeaders Encoding

Created on 19 Aug 2017  路  8Comments  路  Source: amitshekhariitbhu/Fast-Android-Networking

I have tried to do the following even I tested it in the browser which was working. MySportsFeeds require username and password to be passed to headers. When I ran the following code, it went to OnError and received the response:
Response{protocol=http/1.1, code=401, message=Unauthorized, url=https://api.mysportsfeeds.com/v1.1/pull/mlb/2017-regular/conference_team_standings.json}

So I am not sure whether addHeaders are working properly or not.

String loginInfo = getString(R.string.username) + ":" + getString(R.string.password);
byte[] encodingByte = Base64.encode (loginInfo.getBytes(), Base64.DEFAULT);
String encoding = new String(encodingByte);

    AndroidNetworking.get(getString(R.string.mysportsfeeds_url))
            .addPathParameter(getString(R.string.version_number), getString(R.string.mysportsfeeds_version))
            .addPathParameter(getString(R.string.season_name), String.valueOf(year) + "-" + getString(R.string.regular))
            .addPathParameter(getString(R.string.feeds),getString(R.string.feeds_conference_team_standings))
            .addHeaders("Authorization", "Basic " + encoding)
            .setPriority(Priority.LOW)
            .build()
            .getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.i("tag-response",response.toString());
                }

                @Override
                public void onError(ANError anError) {
                    Log.i("tag-error",anError.getResponse().toString());
                }
            });

Most helpful comment

When you open the url in browser, it asks for the username and password. Put the same username and password like below.

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
            @Override            
            public Request authenticate(Route route, Response response) throws IOException {
                return response.request().newBuilder()
                        .header("Authorization", Credentials.basic(username, password))
                        .build();
            }
        })
        .build();


AndroidNetworking.get(url)
        .setOkHttpClient(okHttpClient)
        .build()...

All 8 comments

Try this

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
            @Override            
            public Request authenticate(Route route, Response response) throws IOException {
                return response.request().newBuilder()
                        .header("Authorization", "Basic " + encoding)
                        .build();
            }
        })
        .build();


AndroidNetworking.get(url)
        .setOkHttpClient(okHttpClient)
        .build()...

Same error based on the code you provided above. I do not know how to put the logininfo into address in the browser. MySportsFeeds mention to put it in headers.

When you open the url in browser, it asks for the username and password. Put the same username and password like below.

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
            @Override            
            public Request authenticate(Route route, Response response) throws IOException {
                return response.request().newBuilder()
                        .header("Authorization", Credentials.basic(username, password))
                        .build();
            }
        })
        .build();


AndroidNetworking.get(url)
        .setOkHttpClient(okHttpClient)
        .build()...

Credentials.basic helps. However, I got it still goes to OnError and I checked on anError.toString(). It returns JSON value. Why doesn't it go to OnResponse instead of OnError?

AndroidNetworking.get(getString(R.string.mysportsfeeds_url))
.addPathParameter(getString(R.string.version_number), getString(R.string.mysportsfeeds_version))
.addPathParameter(getString(R.string.season_name), String.valueOf(year) + "-" + getString(R.string.regular))
.addPathParameter(getString(R.string.feeds),getString(R.string.feeds_conference_team_standings))
//.setOkHttpClient(okHttpClient)
.addHeaders("Authorization", Credentials.basic(getString(R.string.username),getString(R.string.password)))
.setPriority(Priority.LOW)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
Log.i("tag-response",response.toString());
}

                @Override
                public void onError(ANError anError) {
                    Log.i("tag-error",anError.toString());
                }
            });

What status code your server is sending? 200? It must not be 200 I think, so it is coming in onError.

There was no error number from response. Response was null. so I use anError.toString() which returned full json value. But it does not matter since I found out. that getAsJSONArray does not work well here. I tried using getAsString and it worked!

Hi ,
I am getting Error when the "=" string is available in Basic c3JyQGZpbmRyb2lkcy5jb206aW5zZWN1cmUxOEs=

Peace on you reader!

I was making a login request with Basic Auth but it didn't go to onResponse(JsonObject response) except it went to failure part and showed me
"NULL", "Input Parameters are missing" on anError.getMessage() and anError.getDetailError() respectively. Moreover, I already set okHttpClient as referred by @amitshekhariitbhu but still didn't work. The authenticator was not calling authenticator(route, respnse) method.

After searching countless times, I found a solution to resolve my above Error. Just intercept your Basic auth like below

import java.io.IOException;

import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BasicInterceptor implements Interceptor {

    private static BasicInterceptor instance;

    public static BasicInterceptor getInstance(String username, String password) {
        if(instance == null)
            instance = new BasicInterceptor(username, password);

        return instance;
    }

    private String credential;

    private BasicInterceptor(String username, String password){
        this.credential = Credentials.basic(username, password);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request authRequest = request.newBuilder().header("Authorization", credential).build();
        return chain.proceed(authRequest);
    }

}

and then add this interceptor to your okHttpClient like this;

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(BasicInterceptor.getInstance(username, password)).build();

I hope this may help you as well... Happy Coding...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ahaneef29 picture ahaneef29  路  7Comments

MohadFarhan picture MohadFarhan  路  5Comments

GulajavaMinistudio picture GulajavaMinistudio  路  3Comments

stridercheng picture stridercheng  路  6Comments

bryant1410 picture bryant1410  路  9Comments