Search in sources :

Example 41 with okhttp3

use of okhttp3 in project BBS-Android by bdpqchen.

the class RxDoHttpClient method getUnsafeBuilder.

// 由于https在连接的过程中会遇到
//javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
//由于无证书的连接是不可信的,在此,建立Okhttp3连接时,选择信任所有的证书。参照
//https://blog.ijustyce.win/post/retrofit2%E4%B9%8Bhttps.html
public static OkHttpClient.Builder getUnsafeBuilder() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier((hostname, session) -> true);
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 42 with okhttp3

use of okhttp3 in project smartmodule by carozhu.

the class HttpDownloadHelper method creatService.

public <S> S creatService(Class<S> serviceClass, final ProgressListener progressListener) {
    //给httpClient添加拦截器
    httpClient.addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response originalResponse = chain.proceed(chain.request());
            ProgressResponseBody responseBody = new ProgressResponseBody(originalResponse.body(), progressListener);
            return originalResponse.newBuilder().body(responseBody).build();
        }
    });
    Retrofit retrofit = builder.build();
    return retrofit.create(serviceClass);
}
Also used : Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 43 with okhttp3

use of okhttp3 in project Varis-Android by dkhmelenko.

the class TestAuthPresenter method testTwoFactorAuth.

@Test
public void testTwoFactorAuth() {
    final String login = "login";
    final String password = "password";
    String auth = EncryptionUtils.generateBasicAuthorization(login, password);
    // rules for throwing a request for 2-factor auth
    final String expectedUrl = "https://sample.org";
    Request rawRequest = new Request.Builder().url(expectedUrl).build();
    okhttp3.Response rawResponse = new okhttp3.Response.Builder().request(rawRequest).message("no body").protocol(Protocol.HTTP_1_1).code(401).header(GithubApiService.TWO_FACTOR_HEADER, "required").build();
    Response response = Response.error(ResponseBody.create(null, ""), rawResponse);
    HttpException exception = new HttpException(response);
    when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), any(AuthorizationRequest.class))).thenReturn(Single.error(exception));
    mAuthPresenter.login(login, password);
    verify(mAuthView).showTwoFactorAuth();
    // rules for handling 2-factor auth continuation
    final String securityCode = "123456";
    final String gitHubToken = "gitHubToken";
    Authorization authorization = new Authorization();
    authorization.setToken(gitHubToken);
    authorization.setId(1L);
    when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), eq(securityCode), any(AuthorizationRequest.class))).thenReturn(Single.just(authorization));
    final String accessToken = "token";
    AccessTokenRequest request = new AccessTokenRequest();
    request.setGithubToken(gitHubToken);
    AccessToken token = new AccessToken();
    token.setAccessToken(accessToken);
    when(mTravisRestClient.getApiService().auth(request)).thenReturn(Single.just(token));
    when(mGitHubRestClient.getApiService().deleteAuthorization(auth, String.valueOf(authorization.getId()))).thenReturn(null);
    mAuthPresenter.twoFactorAuth(securityCode);
    verify(mAuthView, times(2)).hideProgress();
    verify(mAuthView).finishView();
}
Also used : Response(retrofit2.Response) Authorization(com.khmelenko.lab.varis.network.response.Authorization) AuthorizationRequest(com.khmelenko.lab.varis.network.request.AuthorizationRequest) AccessToken(com.khmelenko.lab.varis.network.response.AccessToken) AuthorizationRequest(com.khmelenko.lab.varis.network.request.AuthorizationRequest) Request(okhttp3.Request) AccessTokenRequest(com.khmelenko.lab.varis.network.request.AccessTokenRequest) HttpException(retrofit2.HttpException) AccessTokenRequest(com.khmelenko.lab.varis.network.request.AccessTokenRequest) Test(org.junit.Test)

Example 44 with okhttp3

use of okhttp3 in project curb by irijwj.

the class RetrofitGetData method postCreatedSD.

public static String postCreatedSD(String para_s, final File para_file) {
    RequestBody description = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), para_s);
    RequestBody lc_requestFile = RequestBody.create(okhttp3.MediaType.parse("multipart/form-data"), para_file);
    MultipartBody.Part lc_part = MultipartBody.Part.createFormData("image", para_file.getName(), lc_requestFile);
    Call<String> lc_stringCall = serverInterface.postCreatedSD(description, lc_part);
    Response<String> lc_stringResponse;
    String postResult = null;
    try {
        lc_stringResponse = lc_stringCall.execute();
        if (lc_stringResponse.isSuccessful())
            postResult = lc_stringResponse.body();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return postResult;
}
Also used : MultipartBody(okhttp3.MultipartBody) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 45 with okhttp3

use of okhttp3 in project curb by irijwj.

the class RetrofitGetData method postCreateInformation.

public static String postCreateInformation(@NonNull String userId, @NonNull String information) {
    RequestBody lc_requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), information);
    Call<String> lc_stringCall = serverInterface.postCreateInformation(lc_requestBody, userId);
    Response<String> lc_response = null;
    try {
        lc_response = lc_stringCall.execute();
    } catch (IOException para_e) {
        para_e.printStackTrace();
    }
    if (lc_response != null && lc_response.isSuccessful() && lc_response.body() != null)
        return lc_response.body();
    else
        return null;
}
Also used : IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)25 IOException (java.io.IOException)20 Test (org.junit.Test)16 ResponseBody (okhttp3.ResponseBody)12 OkHttpClient (okhttp3.OkHttpClient)10 Response (okhttp3.Response)9 RequestBody (okhttp3.RequestBody)8 MockResponse (okhttp3.mockwebserver.MockResponse)8 Call (okhttp3.Call)5 Interceptor (okhttp3.Interceptor)5 Map (java.util.Map)4 Retrofit (retrofit2.Retrofit)4 Header (retrofit2.http.Header)4 List (java.util.List)3 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)3 Response (retrofit2.Response)3 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)3 HashMap (java.util.HashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Level (java.util.logging.Level)2