Search in sources :

Example 16 with Builder

use of okhttp3.Request.Builder in project Gradle-demo by Arisono.

the class RetrofitImpl method initClient.

@Override
public void initClient() {
    // 本类保证初始化一次,减少系统开销
    Builder okBuilder = new OkHttpClient.Builder().connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS).readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS).writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS).sslSocketFactory(OkhttpUtils.createSSLSocketFactory(), // 信任所有证书
    new TrustAllCerts()).hostnameVerifier(new TrustAllHostnameVerifier());
    LogInterceptor logInterceptor = new LogInterceptor();
    logInterceptor.setBuilder(mbuilder);
    okBuilder.addInterceptor(logInterceptor);
    if (mbuilder.getCacheFileSize() != 0) {
        okBuilder.cache(new Cache(mbuilder.getCacheFile(), mbuilder.getCacheFileSize()));
        okBuilder.addInterceptor(new CacheInterceptor(String.valueOf(mbuilder.getCacheTime()), mbuilder.getCacheType()));
    }
    //后期缓存策略改进
    switch(mbuilder.getCacheType()) {
        case CacheType.ONLY_NETWORK:
            OkhttpUtils.println("CacheType.ONLY_NETWORK");
            break;
        case CacheType.ONLY_CACHED:
            OkhttpUtils.println("CacheType.ONLY_CACHED");
            break;
        case CacheType.CACHED_ELSE_NETWORK:
            break;
        case CacheType.NETWORK_ELSE_CACHED:
            break;
        default:
            break;
    }
    OkHttpClient client = okBuilder.build();
    retrofit = new Retrofit.Builder().client(client).baseUrl(mbuilder.getBaseUrl()).addConverterFactory(StringConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Retrofit(retrofit2.Retrofit) TrustAllHostnameVerifier(com.gradle.android.retrofit.OkhttpUtils.TrustAllHostnameVerifier) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.OkHttpClient.Builder) LogInterceptor(com.gradle.android.Interceptor.LogInterceptor) CacheInterceptor(com.gradle.android.Interceptor.CacheInterceptor) TrustAllCerts(com.gradle.android.retrofit.OkhttpUtils.TrustAllCerts) Cache(okhttp3.Cache)

Example 17 with Builder

use of okhttp3.Request.Builder in project Gradle-demo by Arisono.

the class RetrofitUtils method uploads.

public void uploads(Subscriber<Object> s, String url, Map<String, Object> params) {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);
    //追加参数
    for (String key : params.keySet()) {
        Object object = params.get(key);
        if (!(object instanceof File)) {
            builder.addFormDataPart(key, object.toString());
        } else {
            File file = (File) object;
            //其中参数“file”和服务器接收的参数 一一对应,保证多文件上传唯一key不变
            builder.addFormDataPart("file", file.getName(), RequestBody.create(null, file));
        }
    }
    //创建RequestBody
    RequestBody body = builder.build();
    Observable<Object> o = paramService.uploads(url, body);
    toSubscribe(o, s);
}
Also used : MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 18 with Builder

use of okhttp3.Request.Builder in project RichText by zzhoujay.

the class DefaultImageGetter method getDrawable.

@Override
public Drawable getDrawable(final ImageHolder holder, final RichTextConfig config, final TextView textView) {
    final DrawableWrapper drawableWrapper = new DrawableWrapper();
    if (config.cacheType >= CacheType.LAYOUT) {
        Rect rect = loadCacheBound(holder.getSource());
        if (rect != null) {
            holder.setCachedBound(rect);
            drawableWrapper.setBounds(rect);
        }
    } else {
        drawableWrapper.setBounds(0, 0, (int) holder.getScaleWidth(), (int) holder.getScaleHeight());
    }
    if (config.cacheType > CacheType.LAYOUT) {
        Bitmap bitmap = loadCacheBitmap(holder.getSource());
        if (bitmap != null) {
            drawableWrapper.setDrawable(new BitmapDrawable(textView.getResources(), bitmap));
            return drawableWrapper;
        }
    }
    Cancelable cancelable;
    AbstractImageLoader imageLoader;
    if (TextKit.isLocalPath(holder.getSource())) {
        LocalFileImageLoader localFileImageLoader = new LocalFileImageLoader(holder, config, textView, drawableWrapper, this);
        Future<?> future = getExecutorService().submit(localFileImageLoader);
        cancelable = new FutureCancelableWrapper(future);
        imageLoader = localFileImageLoader;
    } else {
        byte[] src = Base64.decode(holder.getSource());
        if (src != null) {
            Base64ImageLoader base64ImageLoader = new Base64ImageLoader(src, holder, config, textView, drawableWrapper, this);
            Future<?> future = getExecutorService().submit(base64ImageLoader);
            cancelable = new FutureCancelableWrapper(future);
            imageLoader = base64ImageLoader;
        } else {
            Request builder = new Request.Builder().url(holder.getSource()).get().build();
            Call call = getClient().newCall(builder);
            CallbackImageLoader callback = new CallbackImageLoader(holder, config, textView, drawableWrapper, this);
            cancelable = new CallCancelableWrapper(call);
            imageLoader = callback;
            call.enqueue(callback);
        }
    }
    checkTarget(textView);
    synchronized (lock) {
        tasks.add(cancelable);
        taskMap.put(imageLoader, cancelable);
    }
    return drawableWrapper;
}
Also used : Call(okhttp3.Call) Rect(android.graphics.Rect) DrawableWrapper(com.zzhoujay.richtext.drawable.DrawableWrapper) Request(okhttp3.Request) BitmapDrawable(android.graphics.drawable.BitmapDrawable) Bitmap(android.graphics.Bitmap)

Example 19 with Builder

use of okhttp3.Request.Builder in project graylog2-server by Graylog2.

the class RemoteInterfaceProvider method get.

public <T> T get(Node node, final String authorizationToken, Class<T> interfaceClass) {
    final OkHttpClient okHttpClient = this.okHttpClient.newBuilder().addInterceptor(chain -> {
        final Request original = chain.request();
        Request.Builder builder = original.newBuilder().header(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString()).method(original.method(), original.body());
        if (authorizationToken != null) {
            builder = builder.header(HttpHeaders.AUTHORIZATION, authorizationToken).header(SessionAuthenticator.X_GRAYLOG_NO_SESSION_EXTENSION, "true");
        }
        return chain.proceed(builder.build());
    }).build();
    final Retrofit retrofit = new Retrofit.Builder().baseUrl(node.getTransportAddress()).addConverterFactory(JacksonConverterFactory.create(objectMapper)).client(okHttpClient).build();
    return retrofit.create(interfaceClass);
}
Also used : Inject(javax.inject.Inject) MediaType(com.google.common.net.MediaType) Request(okhttp3.Request) Node(org.graylog2.cluster.Node) OkHttpClient(okhttp3.OkHttpClient) HttpHeaders(com.google.common.net.HttpHeaders) JacksonConverterFactory(retrofit2.converter.jackson.JacksonConverterFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Retrofit(retrofit2.Retrofit) SessionAuthenticator(org.graylog2.security.realm.SessionAuthenticator) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

Example 20 with Builder

use of okhttp3.Request.Builder in project PokeGOAPI-Java by Grover-c13.

the class RequestHandler method sendInternal.

/**
	 * Sends an already built request envelope
	 *
	 * @param serverResponse the response to append to
	 * @param requests list of ServerRequests to be sent
	 * @param platformRequests list of ServerPlatformRequests to be sent
	 * @param builder the request envelope builder
	 * @throws RequestFailedException if this message fails to send
	 */
private ServerResponse sendInternal(ServerResponse serverResponse, ServerRequest[] requests, ServerPlatformRequest[] platformRequests, RequestEnvelope.Builder builder) throws RequestFailedException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    RequestEnvelope request = builder.build();
    try {
        request.writeTo(stream);
    } catch (IOException e) {
        Log.wtf(TAG, "Failed to write request to bytearray ouput stream. This should never happen", e);
    }
    RequestBody body = RequestBody.create(null, stream.toByteArray());
    okhttp3.Request httpRequest = new okhttp3.Request.Builder().url(apiEndpoint).post(body).build();
    try (Response response = client.newCall(httpRequest).execute()) {
        if (response.code() != 200) {
            throw new RequestFailedException("Got a unexpected http code : " + response.code());
        }
        ResponseEnvelope responseEnvelop;
        try (InputStream content = response.body().byteStream()) {
            responseEnvelop = ResponseEnvelope.parseFrom(content);
        } catch (IOException e) {
            // retrieved garbage from the server
            throw new RequestFailedException("Received malformed response : " + e);
        }
        if (responseEnvelop.getApiUrl() != null && responseEnvelop.getApiUrl().length() > 0) {
            apiEndpoint = "https://" + responseEnvelop.getApiUrl() + "/rpc";
        }
        if (responseEnvelop.hasAuthTicket()) {
            this.authTicket = responseEnvelop.getAuthTicket();
        }
        boolean empty = false;
        StatusCode statusCode = responseEnvelop.getStatusCode();
        if (statusCode != StatusCode.REDIRECT && statusCode != StatusCode.INVALID_AUTH_TOKEN) {
            for (int i = 0; i < responseEnvelop.getReturnsCount(); i++) {
                ByteString returned = responseEnvelop.getReturns(i);
                ServerRequest serverRequest = requests[i];
                if (returned != null) {
                    serverResponse.addResponse(serverRequest.getType(), returned);
                    if (serverRequest.getType() == RequestType.GET_PLAYER) {
                        if (GetPlayerResponse.parseFrom(returned).getBanned()) {
                            throw new BannedException("Cannot send request, your account has been banned!");
                        }
                    }
                } else {
                    empty = true;
                }
            }
        }
        for (int i = 0; i < responseEnvelop.getPlatformReturnsCount(); i++) {
            PlatformResponse platformResponse = responseEnvelop.getPlatformReturns(i);
            ByteString returned = platformResponse.getResponse();
            if (returned != null) {
                serverResponse.addResponse(platformResponse.getType(), returned);
            }
        }
        if (statusCode != StatusCode.OK && statusCode != StatusCode.OK_RPC_URL_IN_RESPONSE) {
            if (statusCode == StatusCode.INVALID_AUTH_TOKEN) {
                try {
                    authTicket = null;
                    api.getAuthInfo(true);
                    return sendInternal(serverResponse, requests, platformRequests);
                } catch (LoginFailedException | InvalidCredentialsException e) {
                    throw new RequestFailedException("Failed to refresh auth token!", e);
                } catch (RequestFailedException e) {
                    throw new RequestFailedException("Failed to send request with refreshed auth token!", e);
                }
            } else if (statusCode == StatusCode.REDIRECT) {
                // API_ENDPOINT was not correctly set, should be at this point, though, so redo the request
                return sendInternal(serverResponse, requests, platformRequests, builder);
            } else if (statusCode == StatusCode.BAD_REQUEST) {
                if (api.getPlayerProfile().isBanned()) {
                    throw new BannedException("Cannot send request, your account has been banned!");
                } else {
                    throw new BadRequestException("A bad request was sent!");
                }
            } else {
                throw new RequestFailedException("Failed to send request: " + statusCode);
            }
        }
        if (empty) {
            throw new RequestFailedException("Received empty response from server!");
        }
    } catch (IOException e) {
        throw new RequestFailedException(e);
    } catch (RequestFailedException e) {
        throw e;
    }
    return serverResponse;
}
Also used : InputStream(java.io.InputStream) ByteString(com.google.protobuf.ByteString) PlatformRequest(POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.PlatformRequest) Request(POGOProtos.Networking.Requests.RequestOuterClass.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) StatusCode(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode) PlatformResponse(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse) Response(okhttp3.Response) GetPlayerResponse(POGOProtos.Networking.Responses.GetPlayerResponseOuterClass.GetPlayerResponse) ResponseEnvelope(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) BannedException(com.pokegoapi.exceptions.request.BannedException) RequestEnvelope(POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope) BadRequestException(com.pokegoapi.exceptions.request.BadRequestException) PlatformResponse(POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass.ResponseEnvelope.PlatformResponse) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)163 Response (okhttp3.Response)120 OkHttpClient (okhttp3.OkHttpClient)91 IOException (java.io.IOException)83 RequestBody (okhttp3.RequestBody)67 Test (org.junit.Test)67 MultipartBody (okhttp3.MultipartBody)35 File (java.io.File)31 Map (java.util.Map)31 MockResponse (okhttp3.mockwebserver.MockResponse)31 HttpUrl (okhttp3.HttpUrl)29 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)27 Call (okhttp3.Call)25 Interceptor (okhttp3.Interceptor)24 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)22 Retrofit (retrofit2.Retrofit)20 Builder (okhttp3.Request.Builder)19 ResponseBody (okhttp3.ResponseBody)18 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)17 Builder (okhttp3.OkHttpClient.Builder)17