Search in sources :

Example 21 with Response

use of retrofit2.Response in project Signal-Android by WhisperSystems.

the class GiphyLoader method loadPage.

@NonNull
public List<GiphyImage> loadPage(int offset) {
    try {
        String url;
        if (TextUtils.isEmpty(searchString))
            url = String.format(getTrendingUrl(), offset);
        else
            url = String.format(getSearchUrl(), offset, Uri.encode(searchString));
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }
        GiphyResponse giphyResponse = JsonUtils.fromJson(response.body().byteStream(), GiphyResponse.class);
        List<GiphyImage> results = giphyResponse.getData();
        if (results == null)
            return new LinkedList<>();
        else
            return results;
    } catch (IOException e) {
        Log.w(TAG, e);
        return new LinkedList<>();
    }
}
Also used : GiphyResponse(org.thoughtcrime.securesms.giph.model.GiphyResponse) Response(okhttp3.Response) GiphyResponse(org.thoughtcrime.securesms.giph.model.GiphyResponse) GiphyImage(org.thoughtcrime.securesms.giph.model.GiphyImage) Request(okhttp3.Request) IOException(java.io.IOException) NonNull(android.support.annotation.NonNull)

Example 22 with Response

use of retrofit2.Response in project Signal-Android by WhisperSystems.

the class OkHttpStreamFetcher method loadData.

@Override
public InputStream loadData(Priority priority) throws Exception {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    responseBody = response.body();
    if (!response.isSuccessful()) {
        throw new IOException("Request failed with code: " + response.code());
    }
    long contentLength = responseBody.contentLength();
    stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
    return stream;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) Map(java.util.Map)

Example 23 with Response

use of retrofit2.Response in project lottie-android by airbnb.

the class AnimationFragment method loadUrl.

private void loadUrl(String url) {
    Request request;
    try {
        request = new Request.Builder().url(url).build();
    } catch (IllegalArgumentException e) {
        onLoadError();
        return;
    }
    if (client == null) {
        client = new OkHttpClient();
    }
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            onLoadError();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) {
                onLoadError();
            }
            try {
                JSONObject json = new JSONObject(response.body().string());
                LottieComposition.Factory.fromJson(getResources(), json, new OnCompositionLoadedListener() {

                    @Override
                    public void onCompositionLoaded(LottieComposition composition) {
                        setComposition(composition, "Network Animation");
                    }
                });
            } catch (JSONException e) {
                onLoadError();
            }
        }
    });
}
Also used : Call(okhttp3.Call) OnCompositionLoadedListener(com.airbnb.lottie.OnCompositionLoadedListener) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) LottieComposition(com.airbnb.lottie.LottieComposition)

Example 24 with Response

use of retrofit2.Response in project chuck by jgilfelt.

the class ChuckInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    HttpTransaction transaction = new HttpTransaction();
    transaction.setRequestDate(new Date());
    transaction.setMethod(request.method());
    transaction.setUrl(request.url().toString());
    transaction.setRequestHeaders(request.headers());
    if (hasRequestBody) {
        if (requestBody.contentType() != null) {
            transaction.setRequestContentType(requestBody.contentType().toString());
        }
        if (requestBody.contentLength() != -1) {
            transaction.setRequestContentLength(requestBody.contentLength());
        }
    }
    transaction.setRequestBodyIsPlainText(!bodyHasUnsupportedEncoding(request.headers()));
    if (hasRequestBody && transaction.requestBodyIsPlainText()) {
        BufferedSource source = getNativeSource(new Buffer(), bodyGzipped(request.headers()));
        Buffer buffer = source.buffer();
        requestBody.writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        if (isPlaintext(buffer)) {
            transaction.setRequestBody(readFromBuffer(buffer, charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
    }
    Uri transactionUri = create(transaction);
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        transaction.setError(e.toString());
        update(transaction, transactionUri);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    // includes headers added later in the chain
    transaction.setRequestHeaders(response.request().headers());
    transaction.setResponseDate(new Date());
    transaction.setTookMs(tookMs);
    transaction.setProtocol(response.protocol().toString());
    transaction.setResponseCode(response.code());
    transaction.setResponseMessage(response.message());
    transaction.setResponseContentLength(responseBody.contentLength());
    if (responseBody.contentType() != null) {
        transaction.setResponseContentType(responseBody.contentType().toString());
    }
    transaction.setResponseHeaders(response.headers());
    transaction.setResponseBodyIsPlainText(!bodyHasUnsupportedEncoding(response.headers()));
    if (HttpHeaders.hasBody(response) && transaction.responseBodyIsPlainText()) {
        BufferedSource source = getNativeSource(response);
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                update(transaction, transactionUri);
                return response;
            }
        }
        if (isPlaintext(buffer)) {
            transaction.setResponseBody(readFromBuffer(buffer.clone(), charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
        transaction.setResponseContentLength(buffer.size());
    }
    update(transaction, transactionUri);
    return response;
}
Also used : Buffer(okio.Buffer) HttpTransaction(com.readystatesoftware.chuck.internal.data.HttpTransaction) Request(okhttp3.Request) Charset(java.nio.charset.Charset) Uri(android.net.Uri) Date(java.util.Date) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 25 with Response

use of retrofit2.Response in project okhttp-OkGo by jeasonlzy.

the class FormUploadActivity method formUpload.

@OnClick(R.id.formUpload)
public void formUpload(View view) {
    ArrayList<File> files = new ArrayList<>();
    if (imageItems != null && imageItems.size() > 0) {
        for (int i = 0; i < imageItems.size(); i++) {
            files.add(new File(imageItems.get(i).path));
        }
    }
    //拼接参数
    //
    OkGo.post(Urls.URL_FORM_UPLOAD).tag(//
    this).headers("header1", //
    "headerValue1").headers("header2", //
    "headerValue2").params("param1", //
    "paramValue1").params("param2", //
    "paramValue2").addFileParams("file", // 这种方式为同一个key,上传多个文件
    files).execute(new JsonCallback<LzyResponse<ServerModel>>() {

        @Override
        public void onBefore(BaseRequest request) {
            super.onBefore(request);
            btnFormUpload.setText("正在上传中...");
        }

        @Override
        public void onSuccess(LzyResponse<ServerModel> responseData, Call call, Response response) {
            handleResponse(responseData.data, call, response);
            btnFormUpload.setText("上传完成");
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            handleError(call, response);
            btnFormUpload.setText("上传出错");
        }

        @Override
        public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            System.out.println("upProgress -- " + totalSize + "  " + currentSize + "  " + progress + "  " + networkSpeed);
            String downloadLength = Formatter.formatFileSize(getApplicationContext(), currentSize);
            String totalLength = Formatter.formatFileSize(getApplicationContext(), totalSize);
            tvDownloadSize.setText(downloadLength + "/" + totalLength);
            String netSpeed = Formatter.formatFileSize(getApplicationContext(), networkSpeed);
            tvNetSpeed.setText(netSpeed + "/S");
            tvProgress.setText((Math.round(progress * 10000) * 1.0f / 100) + "%");
            pbProgress.setMax(100);
            pbProgress.setProgress((int) (progress * 100));
        }
    });
}
Also used : Call(okhttp3.Call) LzyResponse(com.lzy.demo.model.LzyResponse) ArrayList(java.util.ArrayList) Response(okhttp3.Response) LzyResponse(com.lzy.demo.model.LzyResponse) ServerModel(com.lzy.demo.model.ServerModel) BaseRequest(com.lzy.okgo.request.BaseRequest) File(java.io.File) OnClick(butterknife.OnClick)

Aggregations

Response (okhttp3.Response)444 Request (okhttp3.Request)322 Test (org.junit.Test)233 IOException (java.io.IOException)169 Response (retrofit2.Response)150 ResponseBody (okhttp3.ResponseBody)138 ServiceResponse (com.microsoft.rest.ServiceResponse)114 MockResponse (okhttp3.mockwebserver.MockResponse)99 Observable (rx.Observable)99 Call (okhttp3.Call)97 RequestBody (okhttp3.RequestBody)66 OkHttpClient (okhttp3.OkHttpClient)65 Callback (okhttp3.Callback)41 List (java.util.List)40 TestClients.clientRequest (keywhiz.TestClients.clientRequest)37 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)34 HttpUrl (okhttp3.HttpUrl)26 Interceptor (okhttp3.Interceptor)26 Buffer (okio.Buffer)24 ANResponse (com.androidnetworking.common.ANResponse)23