HTTPS 不适用于 OkHttp3 和 Retrofit2

HTTPS not working with OkHttp3 and Retrofit2

好吧,我在连接我的 https URL 时遇到问题,所有这些都适用于邮递员,但我无法使用我的 Android 应用程序,有人可以帮助我吗? 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);
}

我需要验证令牌,如何将其添加到 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);
}
}

提前致谢!

尝试使用此代码 HTTPS 与 OkHttp3 和 Retrofit2 一起工作

创建API界面

public interface API {

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

创建包含 OKHttp3 和 retrofit2 初始化和基础的 apiManager class 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);
   }

 }

在Gradle中添加库

 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'

在MainActivity中添加

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();
 }
}

在AndroidManifest中添加

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

希望对您有所帮助。