Search in sources :

Example 16 with Builder

use of okhttp3.OkHttpClient.Builder in project okhttp by square.

the class URLEncodingTest method backdoorUrlToUri.

private URI backdoorUrlToUri(URL url) throws Exception {
    final AtomicReference<URI> uriReference = new AtomicReference<>();
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    Internal.instance.setCache(builder, new InternalCache() {

        @Override
        public Response get(Request request) throws IOException {
            uriReference.set(request.url().uri());
            throw new UnsupportedOperationException();
        }

        @Override
        public CacheRequest put(Response response) throws IOException {
            return null;
        }

        @Override
        public void remove(Request request) throws IOException {
        }

        @Override
        public void update(Response cached, Response network) {
        }

        @Override
        public void trackConditionalCacheHit() {
        }

        @Override
        public void trackResponse(CacheStrategy cacheStrategy) {
        }
    });
    try {
        HttpURLConnection connection = new OkUrlFactory(builder.build()).open(url);
        connection.getResponseCode();
    } catch (Exception expected) {
        if (expected.getCause() instanceof URISyntaxException) {
            expected.printStackTrace();
        }
    }
    return uriReference.get();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) CacheRequest(okhttp3.internal.cache.CacheRequest) InternalCache(okhttp3.internal.cache.InternalCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Response(okhttp3.Response) OkUrlFactory(okhttp3.OkUrlFactory) HttpURLConnection(java.net.HttpURLConnection) CacheRequest(okhttp3.internal.cache.CacheRequest) CacheStrategy(okhttp3.internal.cache.CacheStrategy)

Example 17 with Builder

use of okhttp3.OkHttpClient.Builder in project EnableHands by LeviWGG.

the class ServiceFactory method getOkhttpClient.

public OkHttpClient getOkhttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
    File cachefile = new File(MyApplication.getMyContext().getExternalCacheDir(), "");
    Cache cache = new Cache(cachefile, 1024 * 1024 * 30);
    builder.cache(cache);
    HttpLogInterceptor httpLogInterceptor = new HttpLogInterceptor();
    builder.addInterceptor(httpLogInterceptor);
    CacheInterceptor cacheInterceptor = new CacheInterceptor();
    builder.addInterceptor(cacheInterceptor);
    builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HttpLogInterceptor(app.main.wangliwei.enablehands.http.interceptor.HttpLogInterceptor) File(java.io.File) CacheInterceptor(app.main.wangliwei.enablehands.http.interceptor.CacheInterceptor) Cache(okhttp3.Cache)

Example 18 with Builder

use of okhttp3.OkHttpClient.Builder in project AndLang by wugemu.

the class HttpU method uploadImgAndParameter.

// 批量上传图片公有方法
public void uploadImgAndParameter(final Context context, Map<String, Object> map, String url, final HttpCallback callback) {
    // mImgUrls为存放图片的url集合
    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
    if (null != map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                if ("images".equals(entry.getKey())) {
                    List<File> list = (List<File>) entry.getValue();
                    for (int i = 0; i < list.size(); i++) {
                        builder.addFormDataPart("image" + i, list.get(i).getName(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
                    }
                } else {
                    builder.addFormDataPart(entry.getKey(), entry.getValue().toString());
                }
            }
        }
    }
    // 创建RequestBody
    RequestBody body = builder.build();
    final Request request = new Request.Builder().url(// 地址
    url).post(// 添加请求体
    body).build();
    callback.onBefore(request);
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {
            Log.i("", "");
            handler.post(new Runnable() {

                @Override
                public void run() {
                    callback.onError(request, e, context);
                    callback.onAfter();
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                final String result = response.body().string();
                String cookie = response.headers().get("Set-Cookie");
                Log.d(BaseLangPresenter.TAG, "返回报文cookie:" + cookie);
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onResponse(result);
                        callback.onAfter();
                    }
                });
            } catch (final Exception e) {
                e.printStackTrace();
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onError(request, e, context);
                        callback.onAfter();
                    }
                });
            }
        }
    });
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) MultipartBody(okhttp3.MultipartBody) JSONObject(org.json.JSONObject) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 19 with Builder

use of okhttp3.OkHttpClient.Builder in project apps-android-wikipedia by wikimedia.

the class MockWebServerTest method setUp.

@Before
public void setUp() throws Throwable {
    OkHttpClient.Builder builder = OkHttpConnectionFactory.getClient().newBuilder();
    // Most tests do not expect cached responses.
    // noinspection Since15
    builder.interceptors().removeIf((interceptor) -> interceptor instanceof CacheControlRequestInterceptor);
    okHttpClient = builder.dispatcher(new Dispatcher(new ImmediateExecutorService())).build();
    server.setUp();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) CacheControlRequestInterceptor(org.wikipedia.dataclient.okhttp.CacheControlRequestInterceptor) Dispatcher(okhttp3.Dispatcher) Before(org.junit.Before)

Example 20 with Builder

use of okhttp3.OkHttpClient.Builder in project td-client-java by treasure-data.

the class TestTDHttpClient method failWith429.

private int failWith429(final Optional<String> retryAfterValue, final Optional<Matcher<Date>> retryAfterMatcher) {
    final AtomicInteger requests = new AtomicInteger();
    final TDApiRequest req = TDApiRequest.Builder.GET("/v3/system/server_status").build();
    try {
        client.submitRequest(req, Optional.<String>absent(), new TDHttpRequestHandler<byte[]>() {

            @Override
            public Response send(OkHttpClient httpClient, Request request) throws IOException {
                requests.incrementAndGet();
                Response.Builder builder = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).message("").body(ResponseBody.create(null, "")).code(429);
                if (retryAfterValue.isPresent()) {
                    builder = builder.header("Retry-After", retryAfterValue.get());
                }
                return builder.build();
            }

            @Override
            public byte[] onSuccess(Response response) throws Exception {
                return response.body().bytes();
            }
        });
        fail();
    } catch (TDClientException e) {
        if (!(e instanceof TDClientHttpTooManyRequestsException)) {
            fail("Expected " + TDClientHttpTooManyRequestsException.class + ", got " + e.getClass() + ": " + e.getMessage());
        }
        TDClientHttpTooManyRequestsException tooManyRequestsException = (TDClientHttpTooManyRequestsException) e;
        if (retryAfterMatcher.isPresent()) {
            assertThat(tooManyRequestsException.getRetryAfter().orNull(), retryAfterMatcher.get());
        }
    }
    return requests.get();
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

Request (okhttp3.Request)186 Response (okhttp3.Response)128 OkHttpClient (okhttp3.OkHttpClient)116 IOException (java.io.IOException)97 RequestBody (okhttp3.RequestBody)76 Test (org.junit.Test)68 File (java.io.File)41 MultipartBody (okhttp3.MultipartBody)40 HttpUrl (okhttp3.HttpUrl)39 Map (java.util.Map)34 MockResponse (okhttp3.mockwebserver.MockResponse)32 Call (okhttp3.Call)28 Interceptor (okhttp3.Interceptor)28 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 Retrofit (retrofit2.Retrofit)26 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)25 Builder (okhttp3.OkHttpClient.Builder)23 FormBody (okhttp3.FormBody)20 ResponseBody (okhttp3.ResponseBody)20 Builder (okhttp3.Request.Builder)19