Search in sources :

Example 36 with okhttp3

use of okhttp3 in project retrofit by square.

the class RetrofitTest method callFactoryThrowingPropagates.

@Test
public void callFactoryThrowingPropagates() {
    final RuntimeException cause = new RuntimeException("Broken!");
    okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() {

        @Override
        public okhttp3.Call newCall(Request request) {
            throw cause;
        }
    };
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").callFactory(callFactory).build();
    server.enqueue(new MockResponse());
    CallMethod service = retrofit.create(CallMethod.class);
    Call<ResponseBody> call = service.getResponseBody();
    try {
        call.execute();
        fail();
    } catch (Exception e) {
        assertThat(e).isSameAs(cause);
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Request(okhttp3.Request) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) NonMatchingCallAdapterFactory(retrofit2.helpers.NonMatchingCallAdapterFactory) DelegatingCallAdapterFactory(retrofit2.helpers.DelegatingCallAdapterFactory) NonMatchingConverterFactory(retrofit2.helpers.NonMatchingConverterFactory) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 37 with okhttp3

use of okhttp3 in project retrofit by square.

the class RetrofitTest method callFactoryReturningNullThrows.

@Test
public void callFactoryReturningNullThrows() throws IOException {
    okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() {

        @Override
        public okhttp3.Call newCall(Request request) {
            return null;
        }
    };
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").callFactory(callFactory).build();
    server.enqueue(new MockResponse());
    CallMethod service = retrofit.create(CallMethod.class);
    Call<ResponseBody> call = service.getResponseBody();
    try {
        call.execute();
        fail();
    } catch (NullPointerException e) {
        assertThat(e).hasMessage("Call.Factory returned null.");
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Request(okhttp3.Request) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) NonMatchingCallAdapterFactory(retrofit2.helpers.NonMatchingCallAdapterFactory) DelegatingCallAdapterFactory(retrofit2.helpers.DelegatingCallAdapterFactory) NonMatchingConverterFactory(retrofit2.helpers.NonMatchingConverterFactory) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 38 with okhttp3

use of okhttp3 in project sonarqube by SonarSource.

the class WebhookCallerImpl method followPostRedirect.

/**
   * Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286
   */
private Response followPostRedirect(Response response) throws IOException {
    String location = response.header("Location");
    if (location == null) {
        throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url()));
    }
    HttpUrl url = response.request().url().resolve(location);
    // Don't follow redirects to unsupported protocols.
    if (url == null) {
        throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location));
    }
    Request.Builder redirectRequest = response.request().newBuilder();
    redirectRequest.post(response.request().body());
    response.body().close();
    return okHttpClient.newCall(redirectRequest.url(url).build()).execute();
}
Also used : Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl)

Example 39 with okhttp3

use of okhttp3 in project WordPress-Android by wordpress-mobile.

the class GravatarApi method uploadGravatar.

public static void uploadGravatar(final File file, final String email, final String accessToken, final GravatarUploadListener gravatarUploadListener) {
    Request request = prepareGravatarUpload(email, file);
    createClient(accessToken).newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            if (!response.isSuccessful()) {
                Map<String, Object> properties = new HashMap<>();
                properties.put("network_response_code", response.code());
                // response's body can only be read once so, keep it in a local variable
                String responseBody;
                try {
                    responseBody = response.body().string();
                } catch (IOException e) {
                    responseBody = "null";
                }
                properties.put("network_response_body", responseBody);
                AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_UPLOAD_UNSUCCESSFUL, properties);
                AppLog.w(AppLog.T.API, "Network call unsuccessful trying to upload Gravatar: " + responseBody);
            }
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    if (response.isSuccessful()) {
                        gravatarUploadListener.onSuccess();
                    } else {
                        gravatarUploadListener.onError();
                    }
                }
            });
        }

        @Override
        public void onFailure(okhttp3.Call call, final IOException e) {
            Map<String, Object> properties = new HashMap<>();
            properties.put("network_exception_class", e != null ? e.getClass().getCanonicalName() : "null");
            properties.put("network_exception_message", e != null ? e.getMessage() : "null");
            AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_UPLOAD_EXCEPTION, properties);
            CrashlyticsUtils.logException(e, AppLog.T.API, "Network call failure trying to upload Gravatar!");
            AppLog.w(AppLog.T.API, "Network call failure trying to upload Gravatar!" + (e != null ? e.getMessage() : "null"));
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    gravatarUploadListener.onError();
                }
            });
        }
    });
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) Handler(android.os.Handler) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Call(okhttp3.Call) HashMap(java.util.HashMap) Map(java.util.Map)

Example 40 with okhttp3

use of okhttp3 in project Gradle-demo by Arisono.

the class LogInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Map<String, Object> headers = new HashMap<>();
    Map<String, Object> params = new HashMap<>();
    Map<String, Object> postParm = new HashMap<>();
    //添加公共Header,公共参数
    if (builder != null) {
        headers = builder.getHeaders();
        params = builder.getParams();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                request = request.newBuilder().addHeader(entry.getKey(), String.valueOf(entry.getValue())).build();
            }
        }
        if (!params.isEmpty()) {
            //get请求    添加公共参数
            if (request.method().equals("GET")) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    HttpUrl httpUrl = request.url().newBuilder().addQueryParameter(entry.getKey(), String.valueOf(entry.getValue())).build();
                    request = request.newBuilder().url(httpUrl).build();
                }
            }
            if (request.method().equals("POST")) {
                if (request.body() instanceof FormBody) {
                    FormBody.Builder bodyBuilder = new FormBody.Builder();
                    FormBody formBody = (FormBody) request.body();
                    for (int i = 0; i < formBody.size(); i++) {
                        postParm.put(formBody.encodedName(i), formBody.encodedValue(i));
                        bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    }
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        formBody = bodyBuilder.addEncoded(entry.getKey(), String.valueOf(entry.getValue())).build();
                    }
                    request = request.newBuilder().post(formBody).build();
                }
            }
        }
    }
    Response response = chain.proceed(request);
    okhttp3.MediaType mediaType = response.body().contentType();
    String content = response.body().string();
    if (true) {
        OkhttpUtils.println("|---------------日志打印  start---------------------------|");
        OkhttpUtils.println("请求头:" + JSON.toJSONString(response.request().headers().toMultimap()));
        OkhttpUtils.println("url:" + JSON.toJSONString(response.request().url().toString()));
        OkhttpUtils.println("参数:" + JSON.toJSONString(postParm));
        OkhttpUtils.println("结果:" + content);
        OkhttpUtils.println("|---------------日志打印   end---------------------------|");
    }
    return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
}
Also used : HashMap(java.util.HashMap) Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) Map(java.util.Map) HashMap(java.util.HashMap)

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