Search in sources :

Example 71 with ResponseBody

use of okhttp3.ResponseBody in project Rocket.Chat.Android by RocketChat.

the class DefaultServerPolicyApi method getOkHttpCallback.

private okhttp3.Callback getOkHttpCallback(@NonNull FlowableEmitter<Response<JSONObject>> emitter, @NonNull String protocol) {
    return new okhttp3.Callback() {

        @Override
        public void onFailure(Call call, IOException ioException) {
            if (emitter.isCancelled()) {
                return;
            }
            emitter.onError(ioException);
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            if (emitter.isCancelled()) {
                return;
            }
            if (!response.isSuccessful()) {
                emitter.onNext(new Response<>(false, protocol, null));
                emitter.onComplete();
                return;
            }
            final ResponseBody body = response.body();
            if (body == null || body.contentLength() == 0) {
                emitter.onNext(new Response<>(false, protocol, null));
                emitter.onComplete();
                return;
            }
            try {
                emitter.onNext(new Response<>(true, protocol, new JSONObject(body.string())));
            } catch (Exception e) {
                emitter.onNext(new Response<>(false, protocol, null));
            }
            emitter.onComplete();
        }
    };
}
Also used : Call(okhttp3.Call) JSONObject(org.json.JSONObject) IOException(java.io.IOException) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 72 with ResponseBody

use of okhttp3.ResponseBody in project Tusky by Vavassor.

the class BaseActivity method enablePushNotifications.

protected void enablePushNotifications() {
    Callback<ResponseBody> callback = new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                pushNotificationClient.subscribeToTopic(getPushNotificationTopic());
                pushNotificationClient.connect(BaseActivity.this);
            } else {
                onEnablePushNotificationsFailure(response.message());
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            onEnablePushNotificationsFailure(t.getMessage());
        }
    };
    String deviceToken = pushNotificationClient.getDeviceToken();
    Session session = new Session(getDomain(), getAccessToken(), deviceToken);
    tuskyApi.register(session).enqueue(callback);
}
Also used : Response(okhttp3.Response) Call(retrofit2.Call) Callback(retrofit2.Callback) ResponseBody(okhttp3.ResponseBody) Session(com.keylesspalace.tusky.entity.Session)

Example 73 with ResponseBody

use of okhttp3.ResponseBody in project Tusky by Vavassor.

the class BaseActivity method disablePushNotifications.

protected void disablePushNotifications() {
    Callback<ResponseBody> callback = new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                pushNotificationClient.unsubscribeToTopic(getPushNotificationTopic());
            } else {
                onDisablePushNotificationsFailure();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            onDisablePushNotificationsFailure();
        }
    };
    String deviceToken = pushNotificationClient.getDeviceToken();
    Session session = new Session(getDomain(), getAccessToken(), deviceToken);
    tuskyApi.unregister(session).enqueue(callback);
}
Also used : Response(okhttp3.Response) Call(retrofit2.Call) Callback(retrofit2.Callback) ResponseBody(okhttp3.ResponseBody) Session(com.keylesspalace.tusky.entity.Session)

Example 74 with ResponseBody

use of okhttp3.ResponseBody in project MVPArms by JessYanCoding.

the class RequestIntercept method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (//在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不做操作则返回参数中的request
    mHandler != null)
        request = mHandler.onHttpRequestBefore(chain, request);
    Buffer requestbuffer = new Buffer();
    if (request.body() != null) {
        request.body().writeTo(requestbuffer);
    } else {
        Timber.tag("Request").w("request.body() == null");
    }
    //打印url信息
    Timber.tag("Request").w("Sending Request %s on %n Params --->  %s%n Connection ---> %s%n Headers ---> %s", request.url(), request.body() != null ? parseParams(request.body(), requestbuffer) : "null", chain.connection(), request.headers());
    long t1 = System.nanoTime();
    Response originalResponse = chain.proceed(request);
    long t2 = System.nanoTime();
    //打印响应时间
    Timber.tag("Response").w("Received response  in %.1fms%n%s", (t2 - t1) / 1e6d, originalResponse.headers());
    //读取服务器返回的结果
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    //获取content的压缩类型
    String encoding = originalResponse.headers().get("Content-Encoding");
    Buffer clone = buffer.clone();
    String bodyString;
    //解析response content
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        //content使用gzip压缩
        //解压
        bodyString = ZipHelper.decompressForGzip(clone.readByteArray());
    } else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
        //content使用zlib压缩
        //解压
        bodyString = ZipHelper.decompressToStringForZlib(clone.readByteArray());
    } else {
        //content没有被压缩
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        bodyString = clone.readString(charset);
    }
    Timber.tag("Result").w(jsonFormat(bodyString));
    if (//这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
    mHandler != null)
        return mHandler.onHttpResultResponse(bodyString, chain, originalResponse);
    return originalResponse;
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 75 with ResponseBody

use of okhttp3.ResponseBody in project azure-sdk-for-java by Azure.

the class ComputeNodesImpl method getRemoteLoginSettingsAsync.

/**
     * Gets the settings required for remote login to a compute node.
     *
     * @param poolId The id of the pool that contains the compute node.
     * @param nodeId The id of the compute node for which to obtain the remote login settings.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if callback is null
     * @return the {@link Call} object
     */
public ServiceCall getRemoteLoginSettingsAsync(String poolId, String nodeId, final ServiceCallback<ComputeNodeGetRemoteLoginSettingsResult> serviceCallback) throws IllegalArgumentException {
    if (serviceCallback == null) {
        throw new IllegalArgumentException("ServiceCallback is required for async calls.");
    }
    if (poolId == null) {
        serviceCallback.failure(new IllegalArgumentException("Parameter poolId is required and cannot be null."));
        return null;
    }
    if (nodeId == null) {
        serviceCallback.failure(new IllegalArgumentException("Parameter nodeId is required and cannot be null."));
        return null;
    }
    if (this.client.apiVersion() == null) {
        serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."));
        return null;
    }
    final ComputeNodeGetRemoteLoginSettingsOptions computeNodeGetRemoteLoginSettingsOptions = null;
    Integer timeout = null;
    String clientRequestId = null;
    Boolean returnClientRequestId = null;
    DateTime ocpDate = null;
    DateTimeRfc1123 ocpDateConverted = null;
    if (ocpDate != null) {
        ocpDateConverted = new DateTimeRfc1123(ocpDate);
    }
    Call<ResponseBody> call = service.getRemoteLoginSettings(poolId, nodeId, this.client.apiVersion(), this.client.acceptLanguage(), timeout, clientRequestId, returnClientRequestId, ocpDateConverted, this.client.userAgent());
    final ServiceCall serviceCall = new ServiceCall(call);
    call.enqueue(new ServiceResponseCallback<ComputeNodeGetRemoteLoginSettingsResult>(serviceCallback) {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                serviceCallback.success(getRemoteLoginSettingsDelegate(response));
            } catch (BatchErrorException | IOException exception) {
                serviceCallback.failure(exception);
            }
        }
    });
    return serviceCall;
}
Also used : ComputeNodeGetRemoteLoginSettingsResult(com.microsoft.azure.batch.protocol.models.ComputeNodeGetRemoteLoginSettingsResult) ServiceCall(com.microsoft.rest.ServiceCall) ComputeNodeGetRemoteLoginSettingsOptions(com.microsoft.azure.batch.protocol.models.ComputeNodeGetRemoteLoginSettingsOptions) DateTime(org.joda.time.DateTime) ResponseBody(okhttp3.ResponseBody) DateTimeRfc1123(com.microsoft.rest.DateTimeRfc1123)

Aggregations

ResponseBody (okhttp3.ResponseBody)584 DateTimeRfc1123 (com.microsoft.rest.DateTimeRfc1123)332 DateTime (org.joda.time.DateTime)332 ServiceCall (com.microsoft.rest.ServiceCall)140 Test (org.junit.Test)123 Request (okhttp3.Request)112 Observable (rx.Observable)97 Response (retrofit2.Response)94 ServiceResponse (com.microsoft.rest.ServiceResponse)92 PagedList (com.microsoft.azure.PagedList)80 ServiceResponseWithHeaders (com.microsoft.rest.ServiceResponseWithHeaders)78 List (java.util.List)64 IOException (java.io.IOException)33 Response (okhttp3.Response)33 Buffer (okio.Buffer)33 RequestBody (okhttp3.RequestBody)31 PageImpl (com.microsoft.azure.batch.protocol.models.PageImpl)26 MockResponse (okhttp3.mockwebserver.MockResponse)24 InputStream (java.io.InputStream)19 MultipartBody (okhttp3.MultipartBody)16