コード例 #1
0
  @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));
    }

    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();
  }
  @Override
  protected HttpResponse invoke(HttpURLConnection connection)
      throws IOException, InterruptedException {
    HttpResponse.Builder<?> builder = HttpResponse.builder();
    InputStream in = null;
    try {
      in = consumeOnClose(connection.getInputStream());
    } catch (IOException e) {
      in = bufferAndCloseStream(connection.getErrorStream());
    } catch (RuntimeException e) {
      closeQuietly(in);
      throw propagate(e);
    }

    int responseCode = connection.getResponseCode();
    if (responseCode == 204) {
      closeQuietly(in);
      in = null;
    }
    builder.statusCode(responseCode);
    builder.message(connection.getResponseMessage());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
      String header = entry.getKey();
      // HTTP message comes back as a header without a key
      if (header != null) headerBuilder.putAll(header, entry.getValue());
    }
    ImmutableMultimap<String, String> headers = headerBuilder.build();
    if (in != null) {
      Payload payload = newInputStreamPayload(in);
      contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
      builder.payload(payload);
    }
    builder.headers(filterOutContentHeaders(headers));
    return builder.build();
  }