Search in sources :

Example 91 with Headers

use of okhttp3.Headers in project ignite by apache.

the class RestExecutor method sendRequest0.

/**
 */
private RestResult sendRequest0(String nodeUrl, boolean demo, String path, Map<String, Object> params, Map<String, Object> headers, String body) throws IOException {
    if (demo && AgentClusterDemo.getDemoUrl() == null) {
        try {
            AgentClusterDemo.tryStart().await();
        } catch (InterruptedException ignore) {
            throw new IllegalStateException("Failed to send request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl httpUrl = HttpUrl.parse(url);
    if (httpUrl == null)
        throw new IllegalStateException("Failed to send request because of node URL is invalid: " + url);
    HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
    if (path != null)
        urlBuilder.addPathSegment(path);
    final Request.Builder reqBuilder = new Request.Builder();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
            reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
    }
    if (body != null) {
        MediaType contentType = MediaType.parse("text/plain");
        reqBuilder.post(RequestBody.create(contentType, body));
    } else {
        FormBody.Builder formBody = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null)
                    formBody.add(entry.getKey(), entry.getValue().toString());
            }
        }
        reqBuilder.post(formBody.build());
    }
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        if (resp.isSuccessful()) {
            RestResponseHolder res = MAPPER.readValue(resp.body().byteStream(), RestResponseHolder.class);
            int status = res.getSuccessStatus();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(res.getResponse());
                default:
                    return RestResult.fail(status, res.getError());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in cluster. " + "Please check agent\'s login and password or node port.");
        if (resp.code() == 404)
            return RestResult.fail(STATUS_FAILED, "Failed connect to cluster.");
        return RestResult.fail(STATUS_FAILED, "Failed to execute REST command: " + resp.message());
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 92 with Headers

use of okhttp3.Headers in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method startLoadingLog.

/**
 * Starts loading log file
 *
 * @param jobId Job ID
 */
public void startLoadingLog(long jobId) {
    mJobId = jobId;
    String accessToken = mAppSettings.getAccessToken();
    Single<String> responseSingle;
    if (StringUtils.isEmpty(accessToken)) {
        responseSingle = mRawClient.getApiService().getLog(String.valueOf(mJobId));
    } else {
        String auth = String.format("token %1$s", mAppSettings.getAccessToken());
        responseSingle = mRawClient.getApiService().getLog(auth, String.valueOf(mJobId));
    }
    Disposable subscription = responseSingle.subscribeOn(Schedulers.io()).map(s -> mRawClient.getLogUrl(mJobId)).onErrorResumeNext(new Function<Throwable, SingleSource<String>>() {

        @Override
        public SingleSource<String> apply(@NonNull Throwable throwable) throws Exception {
            String redirectUrl = "";
            if (throwable instanceof HttpException) {
                HttpException httpException = (HttpException) throwable;
                Headers headers = httpException.response().headers();
                for (String header : headers.names()) {
                    if (header.equals("Location")) {
                        redirectUrl = headers.get(header);
                        break;
                    }
                }
                return Single.just(redirectUrl);
            } else {
                return Single.error(throwable);
            }
        }
    }).retry(LOAD_LOG_MAX_ATTEMPT).map(mRawClient::singleStringRequest).map(response -> mLogsParser.parseLog(response.blockingGet())).observeOn(AndroidSchedulers.mainThread()).subscribe((log, throwable) -> {
        if (throwable == null) {
            getView().setLog(log);
        } else {
            getView().showLogError();
            getView().showLoadingError(throwable.getMessage());
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) Headers(okhttp3.Headers) NonNull(io.reactivex.annotations.NonNull) HttpException(retrofit2.HttpException)

Example 93 with Headers

use of okhttp3.Headers in project mobile-sdk-android by meniga.

the class MenigaHttpLogger method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (logLevel == LogLevel.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = logType == LogType.BODY_ONLY || logType == LogType.BODY_AND_HEADERS;
    boolean logHeaders = logType == LogType.HEADERS_ONLY || logType == LogType.BODY_AND_HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    String reqUrl = request.url().toString();
    String requestStartMessage = request.method() + REQUEST_START + reqUrl;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so their values are known.
            if (requestBody.contentType() != null) {
                log(getHeaderString("Content-Type", requestBody.contentType().toString()));
            }
            if (requestBody.contentLength() != -1) {
                log(getHeaderString("Content-Length", Long.toString(requestBody.contentLength())));
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                log(getHeaderString(name, headers.value(i)));
            }
        }
    }
    if (!logBody) {
        log(REQUEST_END + request.method());
    } else if (!hasRequestBody) {
        log(BODY);
        log(NO_BODY);
    } else if (bodyEncoded(request.headers())) {
        log(REQUEST_END + request.method() + " (encoded body omitted)");
    } else {
        Buffer buffer = new Buffer();
        try {
            requestBody.writeTo(buffer);
        } catch (ConcurrentModificationException ex) {
            log("Error logging body - got ConcurrentModificationException");
        }
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        log(BODY);
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log(REQUEST_END + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("<" + requestBody.contentLength() + "-BYTE BINARY BODY OMITTED");
            log(REQUEST_END + request.method());
        }
    }
    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);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    log(RESPONSE_START + reqUrl);
    log("(" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ")");
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            log(getHeaderString(headers.name(i), headers.value(i)));
        }
    }
    if (!logBody) {
        log(RESPONSE_END);
    } else if (!HttpHeaders.hasBody(response)) {
        log(BODY);
        log(NO_BODY);
        log(RESPONSE_END);
    } else if (bodyEncoded(response.headers())) {
        log(BODY);
        log("<ENCODED BODY OMITTED>");
        log(RESPONSE_END);
    } else {
        BufferedSource source = responseBody.source();
        // Buffer the entire body.
        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) {
                log(BODY);
                log("<ERROR DECODING BODY; CHARSET IS LIKELY MALFORMED.>");
                log(RESPONSE_END);
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log(BODY);
            log("<BINARY " + buffer.size() + "-BYTE BODY OMITTED>");
            log(RESPONSE_END);
            return response;
        }
        if (contentLength != 0) {
            log(BODY + " (" + buffer.size() + "-byte body)");
            log(buffer.clone().readString(charset));
        }
        log(RESPONSE_END);
    }
    return response;
}
Also used : Buffer(okio.Buffer) ConcurrentModificationException(java.util.ConcurrentModificationException) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ConcurrentModificationException(java.util.ConcurrentModificationException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 94 with Headers

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

the class HttpLoggingInterceptor method logForRequest.

private void logForRequest(Request request, Connection connection) throws IOException {
    boolean logBody = (printLevel == Level.BODY);
    boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    try {
        String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
        log(requestStartMessage);
        if (logHeaders) {
            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("\t" + headers.name(i) + ": " + headers.value(i));
            }
            log(" ");
            if (logBody && hasRequestBody) {
                if (isPlaintext(requestBody.contentType())) {
                    bodyToString(request);
                } else {
                    log("\tbody: maybe [file part] , too large too print , ignored!");
                }
            }
        }
    } catch (Exception e) {
        OkLogger.e(e);
    } finally {
        log("--> END " + request.method());
    }
}
Also used : HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Protocol(okhttp3.Protocol) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 95 with Headers

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

the class PostTextActivity method postJson.

@OnClick(R.id.postJson)
public void postJson(View view) {
    HashMap<String, String> params = new HashMap<>();
    params.put("key1", "value1");
    params.put("key2", "这里是需要提交的json格式数据");
    params.put("key3", "也可以使用三方工具将对象转成json字符串");
    params.put("key4", "其实你怎么高兴怎么写都行");
    JSONObject jsonObject = new JSONObject(params);
    //
    OkGo.post(Urls.URL_TEXT_UPLOAD).tag(//
    this).headers("header1", //
    "headerValue1").upJson(//
    jsonObject).execute(new DialogCallback<LzyResponse<ServerModel>>(this) {

        @Override
        public void onSuccess(LzyResponse<ServerModel> responseData, Call call, Response response) {
            handleResponse(responseData.data, call, response);
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            handleError(call, response);
        }
    });
}
Also used : LzyResponse(com.lzy.demo.model.LzyResponse) Response(okhttp3.Response) Call(okhttp3.Call) LzyResponse(com.lzy.demo.model.LzyResponse) JSONObject(org.json.JSONObject) ServerModel(com.lzy.demo.model.ServerModel) HashMap(java.util.HashMap) OnClick(butterknife.OnClick)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)58 Response (okhttp3.Response)53 Headers (okhttp3.Headers)46 IOException (java.io.IOException)34 MockResponse (okhttp3.mockwebserver.MockResponse)33 HttpHeaders (okhttp3.internal.http.HttpHeaders)29 ResponseBody (okhttp3.ResponseBody)27 RequestBody (okhttp3.RequestBody)21 List (java.util.List)19 MediaType (okhttp3.MediaType)16 HashMap (java.util.HashMap)15 Map (java.util.Map)15 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Buffer (okio.Buffer)12 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11