Search in sources :

Example 51 with Response

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

the class BaseDetailActivity method handleResponse.

protected <T> void handleResponse(T data, Call call, Response response) {
    StringBuilder sb;
    if (call != null) {
        requestState.setText("请求成功  请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
        Headers requestHeadersString = call.request().headers();
        Set<String> requestNames = requestHeadersString.names();
        sb = new StringBuilder();
        for (String name : requestNames) {
            sb.append(name).append(" : ").append(requestHeadersString.get(name)).append("\n");
        }
        requestHeaders.setText(sb.toString());
    } else {
        requestState.setText("--");
        requestHeaders.setText("--");
    }
    if (data == null) {
        responseData.setText("--");
    } else {
        if (data instanceof String) {
            responseData.setText((String) data);
        } else if (data instanceof List) {
            sb = new StringBuilder();
            List list = (List) data;
            for (Object obj : list) {
                sb.append(obj.toString()).append("\n");
            }
            responseData.setText(sb.toString());
        } else if (data instanceof Set) {
            sb = new StringBuilder();
            Set set = (Set) data;
            for (Object obj : set) {
                sb.append(obj.toString()).append("\n");
            }
            responseData.setText(sb.toString());
        } else if (data instanceof Map) {
            sb = new StringBuilder();
            Map map = (Map) data;
            Set keySet = map.keySet();
            for (Object key : keySet) {
                sb.append(key.toString()).append(" : ").append(map.get(key)).append("\n");
            }
            responseData.setText(sb.toString());
        } else if (data instanceof File) {
            File file = (File) data;
            responseData.setText("数据内容即为文件内容\n下载文件路径:" + file.getAbsolutePath());
        } else if (data instanceof Bitmap) {
            responseData.setText("图片的内容即为数据");
        } else {
            responseData.setText(data.toString());
        }
    }
    if (response != null) {
        Headers responseHeadersString = response.headers();
        Set<String> names = responseHeadersString.names();
        sb = new StringBuilder();
        sb.append("url : ").append(response.request().url()).append("\n\n");
        sb.append("stateCode : ").append(response.code()).append("\n");
        for (String name : names) {
            sb.append(name).append(" : ").append(responseHeadersString.get(name)).append("\n");
        }
        responseHeader.setText(sb.toString());
    } else {
        responseHeader.setText("--");
    }
}
Also used : Bitmap(android.graphics.Bitmap) Set(java.util.Set) Headers(okhttp3.Headers) List(java.util.List) Map(java.util.Map) File(java.io.File)

Example 52 with Response

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

the class HttpLoggingInterceptor method logForResponse.

private Response logForResponse(Response response, long tookMs) {
    Response.Builder builder = response.newBuilder();
    Response clone = builder.build();
    ResponseBody responseBody = clone.body();
    boolean logBody = (printLevel == Level.BODY);
    boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
    try {
        log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
        if (logHeaders) {
            Headers headers = clone.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("\t" + headers.name(i) + ": " + headers.value(i));
            }
            log(" ");
            if (logBody && HttpHeaders.hasBody(clone)) {
                if (isPlaintext(responseBody.contentType())) {
                    String body = responseBody.string();
                    log("\tbody:" + body);
                    responseBody = ResponseBody.create(responseBody.contentType(), body);
                    return response.newBuilder().body(responseBody).build();
                } else {
                    log("\tbody: maybe [file part] , too large too print , ignored!");
                }
            }
        }
    } catch (Exception e) {
        OkLogger.e(e);
    } finally {
        log("<-- END HTTP");
    }
    return response;
}
Also used : Response(okhttp3.Response) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 53 with Response

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

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (printLevel == Level.NONE) {
        return chain.proceed(request);
    }
    //请求日志拦截
    logForRequest(request, chain.connection());
    //执行请求,计算请求时间
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    //响应日志拦截
    return logForResponse(response, tookMs);
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Example 54 with Response

use of okhttp3.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 55 with Response

use of okhttp3.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)

Aggregations

Test (org.junit.Test)471 Response (okhttp3.Response)444 MockResponse (okhttp3.mockwebserver.MockResponse)380 Request (okhttp3.Request)377 ResponseBody (okhttp3.ResponseBody)351 IOException (java.io.IOException)220 DateTime (org.joda.time.DateTime)194 DateTimeRfc1123 (com.microsoft.rest.DateTimeRfc1123)192 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)178 Response (retrofit2.Response)150 ServiceCall (com.microsoft.rest.ServiceCall)140 ServiceResponse (com.microsoft.rest.ServiceResponse)114 Observable (rx.Observable)104 Call (okhttp3.Call)103 List (java.util.List)95 RequestBody (okhttp3.RequestBody)85 PagedList (com.microsoft.azure.PagedList)80 ServiceResponseWithHeaders (com.microsoft.rest.ServiceResponseWithHeaders)78 OkHttpClient (okhttp3.OkHttpClient)78 HttpURLConnection (java.net.HttpURLConnection)47