1

Well, I'm having problems to connect with my https URL, all works with postman, but I can´t do it with my Android App, Can someone help me? Image of code.

public class NetworkUtil{
public static RetrofitInterface getRetrofit(){
    return new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build().create(RetrofitInterface.class);
}
public static RetrofitInterface getRetrofit(String email, String password) {
    String credentials = email + ":" + password;
    String basic = "Basic " + Base64.encodeToString(credentials.getBytes(),Base64.NO_WRAP);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    httpClient.addInterceptor(chain -> {
        Request original = chain.request();
        Request.Builder builder = original.newBuilder()
                .addHeader("Authorization", basic)
                .method(original.method(),original.body());
        return  chain.proceed(builder.build());
    });
    return new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .client(httpClient.build())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build().create(RetrofitInterface.class);
}

I need to authenticate the tokens, how can i add that to the okhttp?

public static RetrofitInterface getRetrofit(String token) {
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    httpClient.addInterceptor(chain -> {
        Request original = chain.request();
        Request.Builder builder = original.newBuilder()
                .addHeader("x-access-token", token)
                .method(original.method(),original.body());
        return  chain.proceed(builder.build());
    });
    return new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build().create(RetrofitInterface.class);
}
}

Thanks in advance!

Chomona
  • 23
  • 1
  • 8

1 Answers1

1

Try to use this code HTTPS working with OkHttp3 and Retrofit2

create API interface

public interface API {

@GET("/users/{user}")
Observable<Result<User>> getUser(@Path("user") String user);
}

create apiManager class which contains OKHttp3 and retrofit2 initialization and base url

public class ApiManager {

Context context;
public static final String BASE_URL = "https://api.github.com/";


private OkHttpClient okHttpClient;
private Authenticator authenticator = new Authenticator() {
    @Override
    public Request authenticate(Route route, Response response) {
        return null;
    }
};


private ApiManager() {
}

public void setAuthenticator(Authenticator authenticator) {
    this.authenticator = authenticator;
}


public static class Builder {
    String email, password;
    ApiManager apiManager = new ApiManager();

    public Builder setAuthenticator(Authenticator authenticator) {
        apiManager.setAuthenticator(authenticator);
        return this;
    }

    public ApiManager build(String param_email, String param_password) {
        this.email = param_email;
        this.password = param_password;
        return apiManager.newInstance(email, password);
    }

}

public class RequestTokenInterceptor implements Interceptor {
    String email, password;
    String credentials, basic;
    public RequestTokenInterceptor(String email, String password) {
        this.email = email;
        this.password = password;
        credentials = email + ":" + password;
        basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
    }



    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder builder = original.newBuilder()
                .addHeader("Authorization", basic)
                .method(original.method(), original.body());
        return chain.proceed(builder.build());
    }
}

private ApiManager newInstance(String email, String password) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.i("http", message);
        }
    });
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);


    okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .addInterceptor(new RequestTokenInterceptor(email, password))
            .authenticator(authenticator)
            .build();


    return this;
}


public <T> T createRest(Class<T> t) {
    Retrofit retrofit = new Retrofit.Builder()

            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(okHttpClient)
            .build();

    return retrofit.create(t);
   }

 }

in Gradle add the libraries

 compile 'com.squareup.okhttp3:okhttp:3.4.1'
 compile 'com.squareup.okhttp3:okhttp-urlconnection:3.4.1'
 compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
 compile 'com.squareup.okhttp3:okhttp-ws:3.4.1'
 compile 'com.squareup.retrofit2:retrofit:2.0.2'
 compile 'com.squareup.retrofit2:converter-gson:2.0.2'
 compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

In MainActivity add

public class MainActivity extends AppCompatActivity {

private ProgressDialog feedbackDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    feedbackDialog = new ProgressDialog(this);
    feedbackDialog.setCanceledOnTouchOutside(false);

    getUser();
}
public void getUser() {

    API accountAPI4 = createRestApi4();
    if (accountAPI4 != null) {
        showFeedback(getResources().getString(R.string.loading));
        BackgroundThreadObservable.toBackground(accountAPI4.getUser("SafAmin"))
                .subscribe(new Action1<Result<User>>() {
                               @Override
                               public void call(Result<User> user) {
                                   dismissFeedback();
                                   Log.e("GIT_HUB","Github Name :"+user.response().body().getName()+"\nWebsite :"+user.response().body().getBlog());
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   // do something with the error
                                   if (throwable != null) {
                                       dismissFeedback();
                                   }
                               }
                           }
                );
    } else {
        dismissFeedback();
    }
}

public static API createRestApi4() {
    ApiManager apiManager = new ApiManager.Builder().build(email, password);
    return apiManager.createRest(API.class);
}

public void showFeedback(String message) {
    feedbackDialog.setMessage(message);

    feedbackDialog.show();
}

public void dismissFeedback() {
    feedbackDialog.dismiss();
 }
}

in AndroidManifest add

    <uses-permission android:name="android.permission.INTERNET"/>

Hope it helps.

Safa
  • 473
  • 5
  • 22
  • I need to add an Interceptor for tokens with the httpClient.addInterceptor – Chomona Apr 06 '17 at 11:36
  • Code edited with your interceptor, please add your actual "email" & "password". hope this helps. – Safa Apr 06 '17 at 12:01
  • I'm taking the email and password from an EditText on my login Activity. – Chomona Apr 06 '17 at 13:48
  • I use the methods of RetrofitInterface getRetrofit() to get the email and password. I'm trying to get both parameters, but i don't know how to got it. – Chomona Apr 06 '17 at 14:01
  • check the updates in `MainActivity` and `apiMannager` .. hope these help you. – Safa Apr 09 '17 at 08:19