Search in sources :

Example 11 with Headers

use of okhttp3.Headers 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 12 with Headers

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

use of okhttp3.Headers in project realm-java by realm.

the class HttpUtils method stopSyncServer.

public static void stopSyncServer() throws Exception {
    Request request = new Request.Builder().url(STOP_SERVER).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);
    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
        RealmLog.debug(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }
    RealmLog.debug(response.body().string());
}
Also used : Response(okhttp3.Response) Headers(okhttp3.Headers) Request(okhttp3.Request) IOException(java.io.IOException)

Example 14 with Headers

use of okhttp3.Headers in project realm-java by realm.

the class HttpUtils method startSyncServer.

public static void startSyncServer() throws Exception {
    Request request = new Request.Builder().url(START_SERVER).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);
    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
        RealmLog.debug(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }
    RealmLog.debug(response.body().string());
    // FIXME: Server ready checking should be done in the control server side!
    if (!waitAuthServerReady()) {
        stopSyncServer();
        throw new RuntimeException("Auth server cannot be started.");
    }
}
Also used : Response(okhttp3.Response) Headers(okhttp3.Headers) Request(okhttp3.Request) IOException(java.io.IOException)

Example 15 with Headers

use of okhttp3.Headers in project spring-framework by spring-projects.

the class OkHttp3ClientHttpRequestFactory method buildRequest.

static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method) throws MalformedURLException {
    okhttp3.MediaType contentType = getContentType(headers);
    RequestBody body = (content.length > 0 || okhttp3.internal.http.HttpMethod.requiresRequestBody(method.name()) ? RequestBody.create(contentType, content) : null);
    Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body);
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            builder.addHeader(headerName, headerValue);
        }
    }
    return builder.build();
}
Also used : Request(okhttp3.Request) List(java.util.List) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)55 Response (okhttp3.Response)50 Headers (okhttp3.Headers)43 MockResponse (okhttp3.mockwebserver.MockResponse)33 IOException (java.io.IOException)32 HttpHeaders (okhttp3.internal.http.HttpHeaders)27 ResponseBody (okhttp3.ResponseBody)25 List (java.util.List)19 RequestBody (okhttp3.RequestBody)19 HashMap (java.util.HashMap)14 Map (java.util.Map)14 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 MediaType (okhttp3.MediaType)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11 JSONObject (org.json.JSONObject)11