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:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
private void multipleInterceptors(List<Interceptor> interceptors) throws Exception { server.enqueue(new MockResponse()); interceptors.add(new Interceptor() { @Override/* www . ja v a 2s . c o m*/ public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Response originalResponse = chain .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Android") // 1. Added first. .build()); return originalResponse.newBuilder().addHeader("Response-Interceptor", "Donut") // 4. Added last. .build(); } }); interceptors.add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Response originalResponse = chain .proceed(originalRequest.newBuilder().addHeader("Request-Interceptor", "Bob") // 2. Added second. .build()); return originalResponse.newBuilder().addHeader("Response-Interceptor", "Cupcake") // 3. Added third. .build(); } }); Request request = new Request.Builder().url(server.url("/")).build(); Response response = client.newCall(request).execute(); assertEquals(Arrays.asList("Cupcake", "Donut"), response.headers("Response-Interceptor")); RecordedRequest recordedRequest = server.takeRequest(); assertEquals(Arrays.asList("Android", "Bob"), recordedRequest.getHeaders().values("Request-Interceptor")); }
From source file:com.aix.city.comm.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 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.anony.okhttp.sample.AccessHeaders.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("https://api.github.com/repos/square/okhttp/issues") .header("User-Agent", "OkHttp Headers.java").addHeader("Accept", "application/json; q=0.5") .addHeader("Accept", "application/vnd.github.v3+json").build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println("Server: " + response.header("Server")); System.out.println("Date: " + response.header("Date")); System.out.println("Vary: " + response.headers("Vary")); }
From source file:com.anony.okhttp.sample.AsynchronousGet.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); client.newCall(request).enqueue(new Callback() { @Override//w w w .j av a2 s . c o m public void onFailure(Request request, IOException e) { e.printStackTrace(); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string()); } }); }
From source file:com.anony.okhttp.sample.CustomTrust.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").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++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); }/*from w ww .j av a 2s. c o m*/ System.out.println(response.body().string()); }
From source file:com.anony.okhttp.sample.LoggingInterceptors.java
License:Apache License
public LoggingInterceptors() { client.networkInterceptors().add(new Interceptor() { @Override/*from w ww . j a va 2 s . c o m*/ public Response intercept(Chain chain) throws IOException { long t1 = System.nanoTime(); Request request = chain.request(); logger.info(String.format("Sending request %s on %s%n%s", request.httpUrl(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); logger.info(String.format("Received response for %s in %.1fms%n%s", request.httpUrl(), (t2 - t1) / 1e6d, response.headers())); return response; } }); }
From source file:com.ariadnext.idcheckio.invoker.ApiClient.java
License:Apache License
/** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type//from w w w . jav a 2s . c om * @param response Response * @param returnType Return type * @throws ApiException If the response has a unsuccessful status code or * fail to deserialize the response body * @return Type */ public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful() || response.code() == 303) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } }
From source file:com.baasbox.android.net.OkClient.java
License:Apache License
@Override public HttpResponse execute(HttpRequest request) throws BaasException { String contentType = request.headers.get("Content-Type"); Request.Builder okRequestBuilder = new Request.Builder(); boolean contentLengthSet = false; for (String name : request.headers.keySet()) { if (!contentLengthSet && "Content-Length".equals(name)) { contentLengthSet = true;/* w w w .j a v a 2 s . com*/ } okRequestBuilder.addHeader(name, request.headers.get(name)); } if (!contentLengthSet) { okRequestBuilder.addHeader("Content-Length", "0"); } RequestBody rb; switch (request.method) { case HttpRequest.GET: okRequestBuilder.get(); break; case HttpRequest.POST: rb = buildBody(contentType, request.body); //InputRequestBody rb = new InputRequestBody(contentType,request.body); okRequestBuilder.post(rb); break; case HttpRequest.PUT: rb = buildBody(contentType, request.body); okRequestBuilder.put(rb); break; case HttpRequest.DELETE: okRequestBuilder.delete(); break; case HttpRequest.PATCH: rb = buildBody(contentType, request.body); okRequestBuilder.patch(rb); break; } okRequestBuilder.url(request.url); Request okRequest = okRequestBuilder.build(); try { Response resp = mOkHttp.newCall(okRequest).execute(); Protocol protocol = resp.protocol(); ProtocolVersion pv; switch (protocol) { case HTTP_1_0: pv = new ProtocolVersion("HTTP", 1, 0); break; case HTTP_1_1: pv = new ProtocolVersion("HTTP", 1, 1); break; case HTTP_2: pv = new ProtocolVersion("HTTP", 2, 0); break; case SPDY_3: pv = new ProtocolVersion("spdy", 3, 1); break; default: throw new BaasIOException("Invalid protocol"); } StatusLine line = new BasicStatusLine(pv, resp.code(), resp.message()); BasicHttpResponse bresp = new BasicHttpResponse(line); bresp.setEntity(asEntity(resp)); for (String name : resp.headers().names()) { String val = resp.headers().get(name); bresp.addHeader(name, val); } return bresp; } catch (IOException e) { throw new BaasIOException(e); } }
From source file:com.carlospinan.demoretrofit2.helpers.LoggingInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Log.d(LOG_TAG, String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));/*from w ww . j av a2s.co m*/ Buffer requestBuffer = new Buffer(); if (request.body() != null) { request.body().writeTo(requestBuffer); Log.d(LOG_TAG, requestBuffer.readUtf8()); } Response response = chain.proceed(request); long t2 = System.nanoTime(); Log.d(LOG_TAG, String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); MediaType contentType = response.body().contentType(); String content = response.body().string(); Log.d(LOG_TAG, content); ResponseBody wrappedBody = ResponseBody.create(contentType, content); return response.newBuilder().body(wrappedBody).build(); }
From source file:com.cdancy.artifactory.rest.config.ArtifactoryOkHttpCommandExecutorService.java
License:Apache License
@Override protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException { OkHttpClient requestScopedClient = clientSupplier.get(); requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri())); Response response = requestScopedClient.newCall(nativeRequest).execute(); HttpResponse.Builder<?> builder = HttpResponse.builder(); builder.statusCode(response.code()); builder.message(response.message()); Builder<String, String> headerBuilder = ImmutableMultimap.builder(); Headers responseHeaders = response.headers(); // Check for Artifactory header and init potential file for downstream use File destinationFile = null;//from ww w.j a v a2s. c om String artFileName = responseHeaders.get("X-Artifactory-Filename"); if (artFileName != null) { GAVCoordinates gavCoordinates = ArtifactoryUtils.gavFromURL(nativeRequest.url(), endpoint.get().toURL()); destinationFile = ArtifactoryUtils.getGradleFile(gavCoordinates, artFileName, responseHeaders.get("ETag")); headerBuilder.put(ArtifactoryUtils.LOCATION_HEADER, destinationFile.getAbsolutePath()); } for (String header : responseHeaders.names()) { headerBuilder.putAll(header, responseHeaders.values(header)); } ImmutableMultimap<String, String> headers = headerBuilder.build(); if (response.code() == 204 && response.body() != null) { response.body().close(); } else { if (destinationFile != null) { if (!destinationFile.exists() || (destinationFile.length() != response.body().contentLength())) { InputStream inputStream = null; try { inputStream = response.body().byteStream(); ArtifactoryUtils.resolveInputStream(inputStream, destinationFile); } catch (Exception e) { Throwables.propagate(e); } finally { if (inputStream != null) { inputStream.close(); } } } IOUtils.closeQuietly(response.body().byteStream()); } else { Payload payload = newInputStreamPayload(response.body().byteStream()); contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); builder.payload(payload); } } builder.headers(filterOutContentHeaders(headers)); return builder.build(); }