List of usage examples for com.squareup.okhttp Response headers
Headers headers
To view the source code for com.squareup.okhttp Response headers.
Click Source Link
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 w w.jav a 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:microsoft.aspnet.signalr.client.http.android.AndroidOkHttpConnection.java
License:Open Source License
@Override public HttpConnectionFuture execute(final Request request, final ResponseCallback responseCallback) { mLogger.log("Create new AsyncTask for HTTP Connection", LogLevel.Verbose); final HttpConnectionFuture future = new HttpConnectionFuture(); com.squareup.okhttp.Request okHttpRequest = createRequest(request); final Call call = client.newCall(okHttpRequest); call.enqueue(new Callback() { @Override//from ww w. j av a 2 s .c o m public void onFailure(com.squareup.okhttp.Request request, IOException e) { mLogger.log("Error executing request: " + e.getMessage(), LogLevel.Critical); future.triggerError(e); } @Override public void onResponse(Response response) throws IOException { mLogger.log("Request executed", LogLevel.Verbose); InputStream bodyStream = response.body().byteStream(); Map<String, List<String>> headersMap = response.headers().toMultimap(); try { responseCallback.onResponse(new StreamResponse(bodyStream, response.code(), headersMap)); future.setResult(null); } catch (Exception e) { mLogger.log("Error calling onResponse: " + e.getMessage(), LogLevel.Critical); future.triggerError(e); } } }); future.onCancelled(new Runnable() { @Override public void run() { call.cancel(); } }); return future; }
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); }/* w ww . j a v a 2s. c o m*/ 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.goldenspiral.fetlifeoss.rest.interceptors.LoggingInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); if (enabled) { Log.i(TAG, String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));/*ww w. j a v a 2 s . co m*/ } Response response = chain.proceed(request); long t2 = System.nanoTime(); if (enabled) { Log.i(TAG, String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); } return response; }
From source file:net.ltgt.resteasy.client.okhttp.OkHttpClientEngine.java
License:Apache License
private ClientResponse createResponse(ClientInvocation request, final Response response) { ClientResponse clientResponse = new ClientResponse(request.getClientConfiguration()) { private InputStream stream; @Override// w w w. ja v a 2s. c o m protected InputStream getInputStream() { if (stream == null) { try { stream = response.body().byteStream(); } catch (IOException e) { throw new RuntimeException(e); } } return stream; } @Override protected void setInputStream(InputStream is) { stream = is; } @Override public void releaseConnection() throws IOException { // Stream might have been entirely replaced, so we need to close it independently from response.body() Throwable primaryExc = null; try { if (stream != null) { stream.close(); } } catch (Throwable t) { primaryExc = t; throw t; } finally { if (primaryExc != null) { try { response.body().close(); } catch (Throwable suppressedExc) { primaryExc.addSuppressed(suppressedExc); } } else { response.body().close(); } } } }; clientResponse.setStatus(response.code()); clientResponse.setHeaders(transformHeaders(response.headers())); return clientResponse; }
From source file:net.protyposis.android.mediaplayer.dash.DashParser.java
License:Open Source License
/** * Parses an MPD XML file. This needs to be executed off the main thread, else a * NetworkOnMainThreadException gets thrown. * @param source the URl of an MPD XML file * @return a MPD object// www. j a va2 s .c o m * @throws android.os.NetworkOnMainThreadException if executed on the main thread */ public MPD parse(UriSource source) throws DashParserException { MPD mpd = null; OkHttpClient httpClient = new OkHttpClient(); Headers.Builder headers = new Headers.Builder(); if (source.getHeaders() != null && !source.getHeaders().isEmpty()) { for (String name : source.getHeaders().keySet()) { headers.add(name, source.getHeaders().get(name)); } } Uri uri = source.getUri(); Request.Builder request = new Request.Builder().url(uri.toString()).headers(headers.build()); try { Response response = httpClient.newCall(request.build()).execute(); if (!response.isSuccessful()) { throw new IOException("error requesting the MPD"); } // Determine this MPD's default BaseURL by removing the last path segment (which is the MPD file) Uri baseUrl = Uri.parse(uri.toString().substring(0, uri.toString().lastIndexOf("/") + 1)); // Get the current datetime from the server for live stream time syncing serverDate = response.headers().getDate("Date"); // Parse the MPD file mpd = parse(response.body().byteStream(), baseUrl); } catch (IOException e) { Log.e(TAG, "error downloading the MPD", e); throw new DashParserException("error downloading the MPD", e); } catch (XmlPullParserException e) { Log.e(TAG, "error parsing the MPD", e); throw new DashParserException("error parsing the MPD", e); } return mpd; }
From source file:net.yatomiya.nicherry.services.bbs.ModelUpdateHandler.java
License:Open Source License
private void doOnResponse(Response response) throws IOException { if (httpCall.isCanceled()) throw new IOException("Canceled"); updateEvent.setResponse(response);/*from w w w .j a va2 s. c o m*/ boolean doForeground = false; if (handleValidateResponse(response)) { if (handleBackground(response)) { doForeground = true; } } if (doForeground) { EUtils.asyncExec(() -> { if (bbsService.isDisposed()) return; try { Date lastModified = response.headers().getDate("Last-Modified"); getModel().setLastModifiedInResponseHeader(lastModified == null ? -1 : lastModified.getTime()); if (handleForeground()) { MBBSModel model = getModel(); model.setLastUpdateTime(model.getUpdateTime()); model.setUpdateTime(JUtils.getCurrentTime()); processor.save(); updateEvent.setType(UpdateEvent.Type.UPDATED); } } catch (IOException e) { updateEvent.setType(UpdateEvent.Type.UNKNOWN_ERROR); updateEvent.setException(e); } handleFinished(); }); } else { handleFinished(); } }
From source file:ooo.oxo.mr.net.LoggingInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.d(TAG, String.format("%s\n%s", request, request.headers())); Response response = chain.proceed(request); Log.d(TAG, String.format("%s\n%s", response, response.headers())); return response; }
From source file:org.addhen.birudo.data.net.LoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Timber.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));//from ww w .jav a2s .co m Response response = chain.proceed(request); long t2 = System.nanoTime(); Timber.i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); return response; }
From source file:org.apache.nifi.processors.standard.InvokeHTTP.java
License:Apache License
private void logResponse(ComponentLog logger, URL url, Response response) { logger.debug("\nResponse from remote service:\n\t{}\n{}", new Object[] { url.toExternalForm(), getLogString(response.headers().toMultimap()) }); }