Search in sources :

Example 11 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.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 12 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project okhttp-OkGo by jeasonlzy.

the class DownloadTask method doInBackground.

/** 一旦该方法执行,意味着开始下载了 */
@Override
protected DownloadInfo doInBackground(Void... params) {
    if (isCancelled())
        return mDownloadInfo;
    mPreviousTime = System.currentTimeMillis();
    mDownloadInfo.setNetworkSpeed(0);
    mDownloadInfo.setState(DownloadManager.DOWNLOADING);
    postMessage(null, null);
    long startPos = mDownloadInfo.getDownloadLength();
    Response response;
    try {
        response = mDownloadInfo.getRequest().headers("RANGE", "bytes=" + startPos + "-").execute();
    } catch (IOException e) {
        e.printStackTrace();
        mDownloadInfo.setNetworkSpeed(0);
        mDownloadInfo.setState(DownloadManager.ERROR);
        postMessage("网络异常", e);
        return mDownloadInfo;
    }
    int code = response.code();
    if (code == 404 || code >= 500) {
        mDownloadInfo.setNetworkSpeed(0);
        mDownloadInfo.setState(DownloadManager.ERROR);
        postMessage("服务器数据错误", null);
        return mDownloadInfo;
    }
    //构建下载文件路径,如果有设置,就用设置的,否者就自己创建
    String url = mDownloadInfo.getUrl();
    String fileName = mDownloadInfo.getFileName();
    if (TextUtils.isEmpty(fileName)) {
        fileName = HttpUtils.getNetFileName(response, url);
        mDownloadInfo.setFileName(fileName);
    }
    if (TextUtils.isEmpty(mDownloadInfo.getTargetPath())) {
        File targetFolder = new File(mDownloadInfo.getTargetFolder());
        if (!targetFolder.exists())
            targetFolder.mkdirs();
        File file = new File(targetFolder, fileName);
        mDownloadInfo.setTargetPath(file.getAbsolutePath());
    }
    //检查文件有效性,文件大小大于总文件大小
    if (startPos > mDownloadInfo.getTotalLength()) {
        mDownloadInfo.setNetworkSpeed(0);
        mDownloadInfo.setState(DownloadManager.ERROR);
        postMessage("断点文件异常,需要删除后重新下载", null);
        return mDownloadInfo;
    }
    if (startPos == mDownloadInfo.getTotalLength() && startPos > 0) {
        mDownloadInfo.setProgress(1.0f);
        mDownloadInfo.setNetworkSpeed(0);
        mDownloadInfo.setState(DownloadManager.FINISH);
        postMessage(null, null);
        return mDownloadInfo;
    }
    //设置断点写文件
    File file = new File(mDownloadInfo.getTargetPath());
    ProgressRandomAccessFile randomAccessFile;
    try {
        randomAccessFile = new ProgressRandomAccessFile(file, "rw", startPos);
        randomAccessFile.seek(startPos);
    } catch (Exception e) {
        e.printStackTrace();
        mDownloadInfo.setNetworkSpeed(0);
        mDownloadInfo.setState(DownloadManager.ERROR);
        postMessage("没有找到已存在的断点文件", e);
        return mDownloadInfo;
    }
    //获取流对象,准备进行读写文件
    long totalLength = response.body().contentLength();
    if (mDownloadInfo.getTotalLength() == 0) {
        mDownloadInfo.setTotalLength(totalLength);
    }
    InputStream is = response.body().byteStream();
    //读写文件流
    try {
        download(is, randomAccessFile);
    } catch (IOException e) {
        e.printStackTrace();
        mDownloadInfo.setNetworkSpeed(0);
        mDownloadInfo.setState(DownloadManager.ERROR);
        postMessage("文件读写异常", e);
        return mDownloadInfo;
    }
    //循环结束走到这里,a.下载完成     b.暂停      c.判断是否下载出错
    if (isCancelled()) {
        mDownloadInfo.setNetworkSpeed(0);
        if (//暂停
        isPause)
            //暂停
            mDownloadInfo.setState(DownloadManager.PAUSE);
        else
            //停止
            mDownloadInfo.setState(DownloadManager.NONE);
        postMessage(null, null);
    } else if (file.length() == mDownloadInfo.getTotalLength() && mDownloadInfo.getState() == DownloadManager.DOWNLOADING) {
        mDownloadInfo.setNetworkSpeed(0);
        //下载完成
        mDownloadInfo.setState(DownloadManager.FINISH);
        postMessage(null, null);
    } else if (file.length() != mDownloadInfo.getDownloadLength()) {
        mDownloadInfo.setNetworkSpeed(0);
        //由于不明原因,文件保存有误
        mDownloadInfo.setState(DownloadManager.ERROR);
        postMessage("未知原因", null);
    }
    return mDownloadInfo;
}
Also used : Response(okhttp3.Response) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 13 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project okhttp-OkGo by jeasonlzy.

the class UploadTask method doInBackground.

/** 一旦该方法执行,意味着开始下载了 */
@Override
protected UploadInfo doInBackground(Void... params) {
    if (isCancelled())
        return mUploadInfo;
    mUploadInfo.setNetworkSpeed(0);
    mUploadInfo.setState(UploadManager.UPLOADING);
    postMessage(null, null, null);
    //构建请求体,默认使用post请求上传
    Response response;
    try {
        response = mUploadInfo.getRequest().setCallback(new MergeListener()).execute();
    } catch (IOException e) {
        e.printStackTrace();
        mUploadInfo.setNetworkSpeed(0);
        mUploadInfo.setState(UploadManager.ERROR);
        postMessage(null, "网络异常", e);
        return mUploadInfo;
    }
    if (response.isSuccessful()) {
        //解析过程中抛出异常,一般为 json 格式错误,或者数据解析异常
        try {
            T t = (T) mUploadInfo.getListener().parseNetworkResponse(response);
            mUploadInfo.setNetworkSpeed(0);
            //上传成功
            mUploadInfo.setState(UploadManager.FINISH);
            postMessage(t, null, null);
            return mUploadInfo;
        } catch (Exception e) {
            e.printStackTrace();
            mUploadInfo.setNetworkSpeed(0);
            mUploadInfo.setState(UploadManager.ERROR);
            postMessage(null, "解析数据对象出错", e);
            return mUploadInfo;
        }
    } else {
        mUploadInfo.setNetworkSpeed(0);
        mUploadInfo.setState(UploadManager.ERROR);
        postMessage(null, "数据返回失败", null);
        return mUploadInfo;
    }
}
Also used : Response(okhttp3.Response) IOException(java.io.IOException) IOException(java.io.IOException)

Example 14 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.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 15 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.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)1083 Request (okhttp3.Request)814 IOException (java.io.IOException)434 Test (org.junit.Test)330 Response (retrofit2.Response)319 Call (okhttp3.Call)236 ResponseBody (okhttp3.ResponseBody)208 OkHttpClient (okhttp3.OkHttpClient)192 ServiceResponse (com.microsoft.rest.ServiceResponse)179 RequestBody (okhttp3.RequestBody)128 Observable (rx.Observable)116 Callback (okhttp3.Callback)111 MockResponse (okhttp3.mockwebserver.MockResponse)93 List (java.util.List)89 HttpUrl (okhttp3.HttpUrl)81 LinkHeaders (com.instructure.canvasapi2.utils.LinkHeaders)72 TypeToken (com.google.common.reflect.TypeToken)71 ArrayList (java.util.ArrayList)71 File (java.io.File)70 JSONObject (org.json.JSONObject)65