Search in sources :

Example 66 with Request

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

the class PoolsImpl method updatePropertiesAsync.

/**
     * Updates the properties of a pool.
     *
     * @param poolId The id of the pool to update.
     * @param poolUpdatePropertiesParameter The parameters for the request.
     * @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 updatePropertiesAsync(String poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, final ServiceCallback<Void> 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 (poolUpdatePropertiesParameter == null) {
        serviceCallback.failure(new IllegalArgumentException("Parameter poolUpdatePropertiesParameter 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;
    }
    Validator.validate(poolUpdatePropertiesParameter, serviceCallback);
    final PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = 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.updateProperties(poolId, poolUpdatePropertiesParameter, this.client.apiVersion(), this.client.acceptLanguage(), timeout, clientRequestId, returnClientRequestId, ocpDateConverted, this.client.userAgent());
    final ServiceCall serviceCall = new ServiceCall(call);
    call.enqueue(new ServiceResponseCallback<Void>(serviceCallback) {

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

Example 67 with Request

use of okhttp3.Request 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 68 with Request

use of okhttp3.Request in project AntennaPod by AntennaPod.

the class GpodnetService method uploadChanges.

/**
     * Updates the subscription list of a specific device.
     * <p/>
     * This method requires authentication.
     *
     * @param username The username. Must be the same user as the one which is
     *                 currently logged in.
     * @param deviceId The ID of the device whose subscriptions should be updated.
     * @param added    Collection of feed URLs of added feeds. This Collection MUST NOT contain any duplicates
     * @param removed  Collection of feed URLs of removed feeds. This Collection MUST NOT contain any duplicates
     * @return a GpodnetUploadChangesResponse. See {@link de.danoeh.antennapod.core.gpoddernet.model.GpodnetUploadChangesResponse}
     * for details.
     * @throws java.lang.IllegalArgumentException                           if username, deviceId, added or removed is null.
     * @throws de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException if added or removed contain duplicates or if there
     *                                                                      is an authentication error.
     */
public GpodnetUploadChangesResponse uploadChanges(@NonNull String username, @NonNull String deviceId, @NonNull Collection<String> added, @NonNull Collection<String> removed) throws GpodnetServiceException {
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/api/2/subscriptions/%s/%s.json", username, deviceId), null).toURL();
        final JSONObject requestObject = new JSONObject();
        requestObject.put("add", new JSONArray(added));
        requestObject.put("remove", new JSONArray(removed));
        RequestBody body = RequestBody.create(JSON, requestObject.toString());
        Request.Builder request = new Request.Builder().post(body).url(url);
        final String response = executeRequest(request);
        return GpodnetUploadChangesResponse.fromJSONObject(response);
    } catch (JSONException | MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONArray(org.json.JSONArray) Request(okhttp3.Request) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 69 with Request

use of okhttp3.Request in project AntennaPod by AntennaPod.

the class GpodnetService method uploadEpisodeActions.

/**
     * Updates the episode actions
     * <p/>
     * This method requires authentication.
     *
     * @param episodeActions    Collection of episode actions.
     * @return a GpodnetUploadChangesResponse. See {@link de.danoeh.antennapod.core.gpoddernet.model.GpodnetUploadChangesResponse}
     * for details.
     * @throws java.lang.IllegalArgumentException                           if username, deviceId, added or removed is null.
     * @throws de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException if added or removed contain duplicates or if there
     *                                                                      is an authentication error.
     */
public GpodnetEpisodeActionPostResponse uploadEpisodeActions(@NonNull Collection<GpodnetEpisodeAction> episodeActions) throws GpodnetServiceException {
    String username = GpodnetPreferences.getUsername();
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/api/2/episodes/%s.json", username), null).toURL();
        final JSONArray list = new JSONArray();
        for (GpodnetEpisodeAction episodeAction : episodeActions) {
            JSONObject obj = episodeAction.writeToJSONObject();
            if (obj != null) {
                list.put(obj);
            }
        }
        RequestBody body = RequestBody.create(JSON, list.toString());
        Request.Builder request = new Request.Builder().post(body).url(url);
        final String response = executeRequest(request);
        return GpodnetEpisodeActionPostResponse.fromJSONObject(response);
    } catch (JSONException | MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONArray(org.json.JSONArray) Request(okhttp3.Request) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) GpodnetEpisodeAction(de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeAction) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 70 with Request

use of okhttp3.Request in project AntennaPod by AntennaPod.

the class GpodnetService method getPodcastToplist.

/**
     * Returns the toplist of podcast.
     *
     * @param count of elements that should be returned. Must be in range 1..100.
     * @throws IllegalArgumentException if count is out of range.
     */
public List<GpodnetPodcast> getPodcastToplist(int count) throws GpodnetServiceException {
    if (count < 1 || count > 100) {
        throw new IllegalArgumentException("Count must be in range 1..100");
    }
    try {
        URL url = new URI(BASE_SCHEME, BASE_HOST, String.format("/toplist/%d.json", count), null).toURL();
        Request.Builder request = new Request.Builder().url(url);
        String response = executeRequest(request);
        JSONArray jsonArray = new JSONArray(response);
        return readPodcastListFromJSONArray(jsonArray);
    } catch (JSONException | MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        throw new GpodnetServiceException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Request(okhttp3.Request) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL)

Aggregations

Request (okhttp3.Request)1552 Response (okhttp3.Response)1090 Test (org.junit.Test)948 IOException (java.io.IOException)624 MockResponse (okhttp3.mockwebserver.MockResponse)560 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)556 OkHttpClient (okhttp3.OkHttpClient)343 RequestBody (okhttp3.RequestBody)281 Call (okhttp3.Call)255 ResponseBody (okhttp3.ResponseBody)252 HttpUrl (okhttp3.HttpUrl)186 Test (org.junit.jupiter.api.Test)158 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)142 Buffer (okio.Buffer)138 List (java.util.List)114 Callback (okhttp3.Callback)114 File (java.io.File)105 URI (java.net.URI)101 InputStream (java.io.InputStream)99 JSONObject (org.json.JSONObject)96