List of usage examples for com.squareup.okhttp Headers name
public String name(int index)
From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new MoesifOkHttp2Interceptor()); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/* w ww . j av a 2 s . c o m*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.peach.masktime.module.net.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); LogUtils.i(TAG, "timeoutMs = " + timeoutMs); client.setProxy(Proxy.NO_PROXY); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from w w w.j a va 2s . c o m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.phattn.vnexpressnews.io.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from w w w . j a v a 2s .c om for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, length = responseHeaders.size(); i < length; i++) { final String name = responseHeaders.name(i); final String value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.rafagarcia.countries.backend.webapi.HttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }/*w ww .j a va2s. c o m*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (logBody && hasRequestBody) { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } logger.log(""); logger.log(buffer.readString(charset)); } String endMessage = "--> END " + request.method(); if (logBody && hasRequestBody) { endMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(endMessage); } long startNs = System.nanoTime(); Response response = chain.proceed(request); long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (logBody) { Buffer buffer = new Buffer(); responseBody.source().readAll(buffer); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() > 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } // Since we consumed the original, replace the one-shot body in the response with a new one. response = response.newBuilder() .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build(); } String endMessage = "<-- END HTTP"; if (logBody) { endMessage += " (" + responseBody.contentLength() + "-byte body)"; } logger.log(endMessage); } return response; }
From source file:com.ydh.gva.util.net.volley.toolbox.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); okHttpRequestBuilder.addHeader("clientos", "101"); okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + ""); okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + ""); okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + ""); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from w w w. j a va2 s. c o m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:io.apiman.gateway.platforms.servlet.connectors.ok.HttpURLConnectionImpl.java
License:Apache License
private HttpEngine newHttpEngine(String method, Connection connection, RetryableSink requestBody, Response priorResponse) { // OkHttp's Call API requires a placeholder body; the real body will be streamed separately. RequestBody placeholderBody = HttpMethod.requiresRequestBody(method) ? EMPTY_REQUEST_BODY : null; Request.Builder builder = new Request.Builder().url(getURL()).method(method, placeholderBody); Headers headers = requestHeaders.build(); for (int i = 0, size = headers.size(); i < size; i++) { builder.addHeader(headers.name(i), headers.value(i)); }//from www . j a va 2 s . c o m boolean bufferRequestBody = false; if (HttpMethod.permitsRequestBody(method)) { // Specify how the request body is terminated. if (fixedContentLength != -1) { builder.header("Content-Length", Long.toString(fixedContentLength)); } else if (chunkLength > 0) { builder.header("Transfer-Encoding", "chunked"); } else { bufferRequestBody = true; } // Add a content type for the request body, if one isn't already present. if (headers.get("Content-Type") == null) { builder.header("Content-Type", "application/x-www-form-urlencoded"); } } if (headers.get("User-Agent") == null) { builder.header("User-Agent", defaultUserAgent()); } Request request = builder.build(); // If we're currently not using caches, make sure the engine's client doesn't have one. OkHttpClient engineClient = client; if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) { engineClient = client.clone().setCache(null); } return new HttpEngine(engineClient, request, bufferRequestBody, true, false, connection, null, requestBody, priorResponse); }
From source file:io.macgyver.core.okhttp.LoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE || (!slf4j.isDebugEnabled())) { return chain.proceed(request); }/*from ww w. jav a2s . co m*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; try { RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if (name.equalsIgnoreCase("authorization")) { log(name + ": ************"); } else { // Skip headers from the request body as they are // explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { log(name + ": " + headers.value(i)); } } } if (!logBody || !hasRequestBody) { slf4j.debug("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } log(""); String body = redactRequestBody(buffer.readString(charset)); log(body); log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace } long startNs = System.nanoTime(); Response response = chain.proceed(request); try { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { log("<-- END HTTP"); } else if (!isResponseBodyPrintable(response)) { log("<-- END HTTP (body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(maxPrintableBodySize); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() != 0) { log(""); log(redactResponseBody(buffer.clone().readString(charset))); } log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString()); } return response; }
From source file:library.util.OkHttpStack.java
License:Apache License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); Builder okHttpRequestBuilder = new Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from w ww .j a v a 2 s .c o m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }/*from w w w .j a v a2 s .c om*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; UUID requestId = UUID.randomUUID(); StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n') .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol); if (!logHeaders && requestBody != null) { requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)"); } requestMessage.append('\n'); if (logHeaders) { if (requestBody != null) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n'); } if (requestBody.contentLength() != -1) { requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n'); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name) || "Proxy-Authorization".equalsIgnoreCase(name) || "WWW-Authenticate".equalsIgnoreCase(name)) { requestMessage.append(name).append(": *****\n"); } // Skip headers from the request body as they are explicitly // logged above. else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { requestMessage.append(name).append(": ").append(headers.value(i)).append('\n'); } } if (!logBody || requestBody == null) { requestMessage.append("--> END ").append(requestId).append('\n'); } else if (bodyEncoded(request.headers())) { requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n'); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } requestMessage.append('\n'); if (isPlaintext(buffer)) { requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId) .append(" (").append(requestBody.contentLength()).append("-byte body)\n"); } else { requestMessage.append("--> END ").append(requestId).append(" (binary ") .append(requestBody.contentLength()).append("-byte body omitted)\n"); } } } logger.log(requestMessage.substring(0, requestMessage.length() - 1)); long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- " + requestId + "HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ') .append(response.request().url()).append(" (").append(tookMs).append("ms"); if (!logHeaders) { responseMessage.append(", "); if (contentLength != -1) { responseMessage.append(contentLength).append("-byte"); } else { responseMessage.append("unknown-length"); } responseMessage.append(" body"); } responseMessage.append(")\n"); responseMessage.append(response.code()).append(' ').append(response.message()).append('\n'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n'); } if (!logBody || !HttpEngine.hasBody(response)) { responseMessage.append("<-- END HTTP\n"); } else if (bodyEncoded(response.headers())) { responseMessage.append("<-- END HTTP (encoded body omitted)\n"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (!isPlaintext(buffer)) { responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size()) .append("-byte body omitted)"); logger.log(responseMessage.toString()); return response; } if (contentLength != 0) { responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n'); } responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n"); } } logger.log(responseMessage.substring(0, responseMessage.length() - 1)); return response; }
From source file:net.ltgt.resteasy.client.okhttp.OkHttpClientEngine.java
License:Apache License
private MultivaluedMap<String, String> transformHeaders(Headers headers) { MultivaluedMap<String, String> ret = new CaseInsensitiveMap<>(); for (int i = 0, l = headers.size(); i < l; i++) { ret.add(headers.name(i), headers.value(i)); }// www . j a va 2s . c om return ret; }