List of usage examples for com.squareup.okhttp Response protocol
Protocol protocol
To view the source code for com.squareup.okhttp Response protocol.
Click Source Link
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 ww w . j av a 2 s. com*/ 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 a2 s. co 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, 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); }//from w w w . j a v a 2 s . com 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.yandex.disk.rest.LoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); String hash = Integer.toHexString(chain.hashCode()); String sendPrefix = hash + SEND_PREFIX; String receivePrefix = hash + RECEIVE_PREFIX; if (logWire) { RequestBody requestBody = request.body(); if (requestBody != null) { logger.info(sendPrefix + "request: " + requestBody); Buffer buffer = new Buffer(); requestBody.writeTo(buffer); byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream()); logBuffer(sendPrefix, requestBuffer); }// w w w . j av a 2 s.co m request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build(); } logger.info(sendPrefix + request.method() + " " + request.url()); logger.info(sendPrefix + "on " + chain.connection()); logHeaders(sendPrefix, request.headers()); Response response = chain.proceed(request); logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message()); logHeaders(receivePrefix, response.headers()); if (logWire) { ResponseBody body = response.body(); byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream()); response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build(); logBuffer(receivePrefix, responseBuffer); } 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 ww w .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: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 . j a va2 s. 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:io.minio.MinioClient.java
License:Apache License
/** * Executes given request parameters./*from w ww .j a v a 2 s.c om*/ * * @param method HTTP method. * @param region Amazon S3 region of the bucket. * @param bucketName Bucket name. * @param objectName Object name in the bucket. * @param headerMap Map of HTTP headers for the request. * @param queryParamMap Map of HTTP query parameters of the request. * @param contentType Content type of the request body. * @param body HTTP request body. * @param length Length of HTTP request body. */ private HttpResponse execute(Method method, String region, String bucketName, String objectName, Map<String, String> headerMap, Map<String, String> queryParamMap, String contentType, Object body, int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Request request = createRequest(method, bucketName, objectName, region, headerMap, queryParamMap, contentType, body, length); if (this.accessKey != null && this.secretKey != null) { request = Signer.signV4(request, region, accessKey, secretKey); } if (this.traceStream != null) { this.traceStream.println("---------START-HTTP---------"); String encodedPath = request.httpUrl().encodedPath(); String encodedQuery = request.httpUrl().encodedQuery(); if (encodedQuery != null) { encodedPath += "?" + encodedQuery; } this.traceStream.println(request.method() + " " + encodedPath + " HTTP/1.1"); String headers = request.headers().toString().replaceAll("Signature=([0-9a-f]+)", "Signature=*REDACTED*"); this.traceStream.println(headers); } Response response = this.httpClient.newCall(request).execute(); if (response == null) { if (this.traceStream != null) { this.traceStream.println("<NO RESPONSE>"); this.traceStream.println(END_HTTP); } throw new NoResponseException(); } if (this.traceStream != null) { this.traceStream.println(response.protocol().toString().toUpperCase() + " " + response.code()); this.traceStream.println(response.headers()); } ResponseHeader header = new ResponseHeader(); HeaderParser.set(response.headers(), header); if (response.isSuccessful()) { if (this.traceStream != null) { this.traceStream.println(END_HTTP); } return new HttpResponse(header, response); } ErrorResponse errorResponse = null; // HEAD returns no body, and fails on parseXml if (!method.equals(Method.HEAD)) { try { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } errorResponse = new ErrorResponse(new StringReader(errorXml)); if (this.traceStream != null) { this.traceStream.println(errorXml); } } finally { response.body().close(); } } if (this.traceStream != null) { this.traceStream.println(END_HTTP); } if (errorResponse == null) { ErrorCode ec; switch (response.code()) { case 400: ec = ErrorCode.INVALID_URI; break; case 404: if (objectName != null) { ec = ErrorCode.NO_SUCH_KEY; } else if (bucketName != null) { ec = ErrorCode.NO_SUCH_BUCKET; } else { ec = ErrorCode.RESOURCE_NOT_FOUND; } break; case 501: case 405: ec = ErrorCode.METHOD_NOT_ALLOWED; break; case 409: if (bucketName != null) { ec = ErrorCode.NO_SUCH_BUCKET; } else { ec = ErrorCode.RESOURCE_CONFLICT; } break; case 403: ec = ErrorCode.ACCESS_DENIED; break; default: throw new InternalException("unhandled HTTP code " + response.code() + ". Please report this issue at " + "https://github.com/minio/minio-java/issues"); } errorResponse = new ErrorResponse(ec, bucketName, objectName, request.httpUrl().encodedPath(), header.xamzRequestId(), header.xamzId2()); } // invalidate region cache if needed if (errorResponse.errorCode() == ErrorCode.NO_SUCH_BUCKET) { BucketRegionCache.INSTANCE.remove(bucketName); // TODO: handle for other cases as well // observation: on HEAD of a bucket with wrong region gives 400 without body } throw new ErrorResponseException(errorResponse, 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)); }// w ww .ja va 2 s.co 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:quickbeer.android.next.network.utils.LoginRedirectInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (request.uri().getPath().equals("/Signin_r.asp") && response.isRedirect()) { Log.d(TAG, "Modifying response for login request"); return new Response.Builder().request(request).protocol(response.protocol()).code(200) .message(response.message()).handshake(response.handshake()).headers(response.headers()) .body(response.body()).networkResponse(response.networkResponse()).build(); }/*from www . j a v a 2 s .co m*/ return response; }