List of usage examples for com.squareup.okhttp Headers names
public Set<String> names()
From source file:at.bitfire.dav4android.exception.HttpException.java
License:Open Source License
public HttpException(Response response) { super(response.code() + " " + response.message()); status = response.code();/*from w w w. ja v a 2 s.co m*/ message = response.message(); /* As we don't know the media type and character set of request and response body, only printable ASCII characters will be shown in clear text. Other octets will be shown as "[xx]" where xx is the hex value of the octet. */ // format request Request request = response.request(); StringBuilder formatted = new StringBuilder(); formatted.append(request.method() + " " + request.urlString() + "\n"); Headers headers = request.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (request.body() != null) try { formatted.append("\n"); Buffer buffer = new Buffer(); request.body().writeTo(buffer); while (!buffer.exhausted()) appendByte(formatted, buffer.readByte()); } catch (IOException e) { } this.request = formatted.toString(); // format response formatted = new StringBuilder(); formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n"); headers = response.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (response.body() != null) try { formatted.append("\n"); for (byte b : response.body().bytes()) appendByte(formatted, b); } catch (IOException e) { } this.response = formatted.toString(); }
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 w w w . j a va 2s . 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(); }
From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java
License:Open Source License
/** * Process the response data//from w w w.j a v a2 s .c o m */ private void processResponse(byte[] bResponse, long startTime, long endTime, BaseRequest request, String message, int httpCode, Headers headers) { BaseResponse response = request.getResponse(); try { if (response == null) { // Get response header information String contentType = headers.get("ContentType"); if (StringUtils.isBlank(contentType)) { contentType = ""; } response = TankHttpUtil.newResponseObject(contentType); request.setResponse(response); } // Get response detail information response.setHttpMessage(message); response.setHttpCode(httpCode); // Get response header information for (String key : headers.names()) { response.setHeader(key, headers.get(key)); } if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) { for (HttpCookie cookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore() .getCookies()) { // System.out.println("in processResponse-getCookies"); // System.out.println(cookie.toString()); response.setCookie(cookie.getName(), cookie.getValue()); } } response.setResponseTime(endTime - startTime); String contentType = response.getHttpHeader("Content-Type"); String contentEncode = response.getHttpHeader("Content-Encoding"); if (BaseResponse.isDataType(contentType) && contentEncode != null && contentEncode.toLowerCase().contains("gzip")) { // decode gzip for data types try { GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(bResponse)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); bResponse = out.toByteArray(); } catch (Exception e) { LOG.warn(request.getLogUtil().getLogMessage("cannot decode gzip stream: " + e, LogEventType.System)); } } response.setResponseBody(bResponse); } catch (Exception ex) { LOG.warn("Unable to get response: " + ex.getMessage()); } finally { response.logResponse(); } }
From source file:com.parse.ParseHttpClientTest.java
License:Open Source License
private void doSingleParseHttpClientExecuteWithResponse(int responseCode, String responseStatus, String responseContent, ParseHttpClient client) throws Exception { MockWebServer server = new MockWebServer(); // Make mock response int responseContentLength = responseContent.length(); MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus) .setBody(responseContent);/*from w w w. j a v a 2 s .c om*/ // Start mock server server.enqueue(mockResponse); server.start(); // Make ParseHttpRequest Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("User-Agent", "Parse Android SDK"); String requestUrl = server.getUrl("/").toString(); JSONObject json = new JSONObject(); json.put("key", "value"); String requestContent = json.toString(); int requestContentLength = requestContent.length(); String requestContentType = "application/json"; ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl) .setMethod(ParseHttpRequest.Method.POST) .setBody(new ParseByteArrayHttpBody(requestContent, requestContentType)).setHeaders(requestHeaders) .build(); // Execute request ParseHttpResponse parseResponse = client.execute(parseRequest); RecordedRequest recordedApacheRequest = server.takeRequest(); // Verify request method assertEquals(ParseHttpRequest.Method.POST.toString(), recordedApacheRequest.getMethod()); // Verify request headers, since http library automatically adds some headers, we only need to // verify all parseRequest headers are in recordedRequest headers. Headers recordedApacheHeaders = recordedApacheRequest.getHeaders(); Set<String> recordedApacheHeadersNames = recordedApacheHeaders.names(); for (String name : parseRequest.getAllHeaders().keySet()) { assertTrue(recordedApacheHeadersNames.contains(name)); assertEquals(parseRequest.getAllHeaders().get(name), recordedApacheHeaders.get(name)); } // Verify request body assertEquals(requestContentLength, recordedApacheRequest.getBodySize()); assertArrayEquals(requestContent.getBytes(), recordedApacheRequest.getBody().readByteArray()); // Verify response status code assertEquals(responseCode, parseResponse.getStatusCode()); // Verify response status assertEquals(responseStatus, parseResponse.getReasonPhrase()); // Verify all response header entries' keys and values are not null. for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) { assertNotNull(entry.getKey()); assertNotNull(entry.getValue()); } // Verify response body byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent()); assertArrayEquals(responseContent.getBytes(), content); // Verify response body size assertEquals(responseContentLength, content.length); // Shutdown mock server server.shutdown(); }
From source file:com.yandex.disk.rest.LoggingInterceptor.java
License:Apache License
private void logHeaders(String prefix, Headers headers) { for (String name : headers.names()) { List<String> values = headers.values(name); for (String value : values) { logger.info(prefix + name + ": " + value); }/*from w w w.j av a2s .c o m*/ } }
From source file:es.upv.grycap.opengateway.examples.test.AppDaemonTest.java
License:Apache License
private void testGetObject(final String id, final Waiter waiter) throws URISyntaxException, MalformedURLException { final Http2Client client = isolatedHttp2Client(); client.asyncGetJson(String.format("%s/%s/%s", uri, path, id), false, new Callback() { @Override//from w ww. jav a 2 s . co m public void onResponse(final Response response) throws IOException { waiter.assertTrue(response.isSuccessful()); // check response headers final Headers headers = response.headers(); waiter.assertNotNull(headers); waiter.assertNotNull(headers.names()); waiter.assertThat(headers.names().size(), greaterThan(0)); // check response body waiter.assertThat(response.body().contentLength(), greaterThan(0l)); final String payload = response.body().source().readUtf8(); waiter.assertThat(payload, allOf(notNullValue(), not(equalTo("")))); pw.println(" >> Abbreviated response: " + abbreviate(payload, 32)); // parse and check final Gson gson = new Gson(); if (path.contains("products")) { final Product product = gson.fromJson(payload, Product.class); waiter.assertNotNull(product); waiter.assertThat(product, allOf(notNullValue(), equalTo(getProducts().get(id)))); pw.println(" >> Object response: " + product); } else if (path.contains("shipping")) { final Shipping shipping = gson.fromJson(payload, Shipping.class); waiter.assertNotNull(shipping); waiter.assertThat(shipping, allOf(notNullValue(), equalTo(getShipping().get(id)))); pw.println(" >> Object response: " + shipping); } waiter.resume(); } @Override public void onFailure(final Request request, final IOException throwable) { waiter.fail(throwable); } }); }
From source file:es.upv.grycap.opengateway.examples.test.AppDaemonTest.java
License:Apache License
private void testGetList(final Waiter waiter) { final Http2Client client = isolatedHttp2Client(); client.asyncGetJson(String.format("%s/%s", uri, path), false, new Callback() { @Override//from w w w. j av a 2 s . c o m public void onResponse(final Response response) throws IOException { waiter.assertTrue(response.isSuccessful()); // check response headers final Headers headers = response.headers(); waiter.assertNotNull(headers); waiter.assertNotNull(headers.names()); waiter.assertThat(headers.names().size(), greaterThan(0)); // check response body waiter.assertThat(response.body().contentLength(), greaterThan(0l)); final String payload = response.body().source().readUtf8(); waiter.assertThat(payload, allOf(notNullValue(), not(equalTo("")))); pw.println(" >> Abbreviated response: " + abbreviate(payload, 32)); // parse and check final Gson gson = new Gson(); if (path.contains("products")) { final Type collectionType = new TypeToken<List<Product>>() { }.getType(); final List<Product> products = gson.fromJson(payload, collectionType); waiter.assertNotNull(products); waiter.assertThat(products, allOf(notNullValue(), containsInAnyOrder(getProducts().values().toArray()))); pw.println(" >> Object response: " + products); } else if (path.contains("shipping")) { final Type collectionType = new TypeToken<List<Shipping>>() { }.getType(); final List<Shipping> shipping = gson.fromJson(payload, collectionType); waiter.assertNotNull(shipping); waiter.assertThat(shipping, allOf(notNullValue(), containsInAnyOrder(getShipping().values().toArray()))); pw.println(" >> Object response: " + shipping); } waiter.resume(); } @Override public void onFailure(final Request request, final IOException throwable) { waiter.fail(throwable); } }); }
From source file:feign.okhttp.OkHttpClient.java
License:Apache License
private static Map<String, Collection<String>> toMap(Headers headers) { Map<String, Collection<String>> result = new LinkedHashMap<String, Collection<String>>(headers.size()); for (String name : headers.names()) { // TODO: this is very inefficient as headers.values iterate case insensitively. result.put(name, headers.values(name)); }/* w w w.j av a 2 s . c o m*/ return result; }
From source file:io.minio.Signer.java
License:Apache License
private void setCanonicalHeaders() { this.canonicalHeaders = new TreeMap<>(); Headers headers = this.request.headers(); for (String name : headers.names()) { String signedHeader = name.toLowerCase(); if (!IGNORED_HEADERS.contains(signedHeader)) { this.canonicalHeaders.put(signedHeader, headers.get(name)); }//w ww .j ava 2 s.c o m } this.signedHeaders = Joiner.on(";").join(this.canonicalHeaders.keySet()); }
From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorService.java
License:Apache License
@Override protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException { OkHttpClient requestScopedClient = globalClient.clone(); 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(); for (String header : responseHeaders.names()) { headerBuilder.putAll(header, responseHeaders.values(header)); }// w w w.j ava2s .c om ImmutableMultimap<String, String> headers = headerBuilder.build(); if (response.code() == 204 && response.body() != null) { response.body().close(); } else { Payload payload = newInputStreamPayload(response.body().byteStream()); contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); builder.payload(payload); } builder.headers(filterOutContentHeaders(headers)); return builder.build(); }