com.squareup.okhttp.Request类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(10.5k)|赞(0)|评价(0)|浏览(230)

本文整理了Java中com.squareup.okhttp.Request类的一些代码示例,展示了Request类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Request类的具体详情如下:
包路径:com.squareup.okhttp.Request
类名称:Request

Request介绍

暂无

代码示例

代码示例来源:origin: facebook/stetho

@Override
public String method() {
 return mRequest.method();
}

代码示例来源:origin: facebook/stetho

@Nullable
@Override
public byte[] body() throws IOException {
 RequestBody body = mRequest.body();
 if (body == null) {
  return null;
 }
 OutputStream out = mRequestBodyHelper.createBodySink(firstHeaderValue("Content-Encoding"));
 BufferedSink bufferedSink = Okio.buffer(Okio.sink(out));
 try {
  body.writeTo(bufferedSink);
 } finally {
  bufferedSink.close();
 }
 return mRequestBodyHelper.getDisplayBody();
}

代码示例来源:origin: facebook/stetho

@Nullable
 @Override
 public String firstHeaderValue(String name) {
  return mRequest.header(name);
 }
}

代码示例来源:origin: tomahawk-player/tomahawk-android

public JsonElement get(JsonObject object, String memberName) throws IOException {
    JsonElement element = object.get(memberName);
    if (element == null) {
      JsonObject links = object.getAsJsonObject("links");
      if (links != null && links.has(memberName)) {
        Request request = new Request.Builder()
            .url(HATCHET_BASE_URL + links.get(memberName).getAsString())
            .build();
        Log.d(TAG, "following link: " + request.urlString());
        Response response = mOkHttpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
          throw new IOException("API request with URL '" + request.urlString()
              + "' not successful. Code was " + response.code());
        }
        try {
          element = GsonHelper.get().fromJson(
              response.body().charStream(), JsonElement.class);
        } catch (JsonIOException | JsonSyntaxException e) {
          throw new IOException(e);
        } finally {
          response.body().close();
        }
      }
    }
    return element;
  }
}

代码示例来源:origin: cn-ljb/rxjava_for_android

boolean logHeaders = logBody || level == Level.HEADERS;
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
StringBuilder requestStartMessage = new StringBuilder();
requestStartMessage.append("--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol));
if (!logHeaders && hasRequestBody) {
  requestStartMessage.append(" (" + requestBody.contentLength() + BYTE_BODY);
  Headers headers = request.headers();
  for (int i = 0, count = headers.size(); i < count; i++) {
    String name = headers.name(i);
    logger.log(END + request.method());
  } else if (bodyEncoded(request.headers())) {
    logger.log(END + request.method() + " (encoded body omitted)");
  } else {
    Buffer buffer = new Buffer();
    logger.log(END + request.method()
        + " (" + requestBody.contentLength() + BYTE_BODY);
ResponseBody responseBody = response.body();
logger.log("<-- " + response.code() + ' ' + response.message() + ' '
    + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", "
    + responseBody.contentLength() + "-byte body" : "") + ')');

代码示例来源:origin: kubernetes-client/java

@Override public Response intercept(Chain chain) throws IOException {
  Request originalRequest = chain.request();
  if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
    return chain.proceed(originalRequest);
  }
  Request compressedRequest = originalRequest.newBuilder()
                        .header("Content-Encoding", "gzip")
                        .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
                        .build();
  return chain.proceed(compressedRequest);
}

代码示例来源:origin: com.stanfy.helium/helium

@Override
public Response intercept(final Chain chain) throws IOException {
 Request request = chain.request();
 LOG.info("---> HTTP {} {}", request.method(), request.urlString());
 logHeaders(request.headers());
 if (request.body() != null) {
  Buffer bodyBuffer = new Buffer();
  request.body().writeTo(bodyBuffer);
  final MediaType contentType = request.body().contentType();
  request = request.newBuilder()
    .method(request.method(), new RequestBody() {
     @Override
     public long contentLength() throws IOException {
 long time = System.currentTimeMillis() - start;
 LOG.info("<--- HTTP {} {} ({}ms)", request.urlString(), response.code(), time);
 logHeaders(response.headers());
 BufferedSource source = response.body().source();
 try {
  final ByteString body = source.readByteString();

代码示例来源:origin: io.macgyver/macgyver-core

RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
String requestStartMessage = "--> " + request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol);
if (!logHeaders && hasRequestBody) {
  requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
  Headers headers = request.headers();
  for (int i = 0, count = headers.size(); i < count; i++) {
    String name = headers.name(i);
    slf4j.debug("--> END " + request.method());
  } else if (bodyEncoded(request.headers())) {
    log("--> END " + request.method() + " (encoded body omitted)");
  } else {
    Buffer buffer = new Buffer();
    log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
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" : "") + ')');

代码示例来源:origin: com.stanfy.helium/helium

private static String getRequestInfo(final Request request, final Response response) {
 final StringBuilder stringBuilder = new StringBuilder();
 stringBuilder.append("\nRequest info: ");
 stringBuilder.append(request.method())
   .append(' ')
   .append(request.urlString())
   .append('\n');
 dumpHeaders(request.headers(), stringBuilder);
 if (request.body() != null) {
  final String loggedEntity = requestBodyToString(request.body());
  if (loggedEntity != null) {
   stringBuilder.append('\n').append(loggedEntity).append('\n');
  }
 }
 stringBuilder.append('\n');
 if (response == null) {
  stringBuilder.append("Response info is not available.");
 } else {
  stringBuilder.append("Response info:\n")
    .append(response.code()).append(" ").append(response.message()).append("\n");
  dumpHeaders(response.headers(), stringBuilder);
  stringBuilder
    .append('\n')
    .append(responseBodyToString(response.body())).append('\n');
 }
 return stringBuilder.toString();
}

代码示例来源:origin: com.squareup.retrofit/retrofit

static Response parseResponse(com.squareup.okhttp.Response response) {
 return new Response(response.request().urlString(), response.code(), response.message(),
   createHeaders(response.headers()), createResponseBody(response.body()));
}

代码示例来源:origin: kubernetes-client/java

byte[] bytes = encode(deleteOptions, "v1", "DeleteOptions");
request =
  request.newBuilder().delete(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes)).build();
Response resp = apiClient.getHttpClient().newCall(request).execute();
Unknown u = parse(resp.body().byteStream());
resp.body().close();

代码示例来源:origin: NightscoutFoundation/xDrip

Request copy = original.newBuilder().build();
Request modifiedRequest = original.newBuilder()
    .header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0")
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .build();
Log.d(TAG, "Sending request: " + modifiedRequest.toString());
Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
Log.d(TAG, "Request body: " + buffer.readUtf8());
Log.d(TAG, "Received response: " + response.toString());
if (response.body() != null) {
  MediaType contentType = response.body().contentType();
  String bodyString = response.body().string();
  Log.d(TAG, "Response body: " + bodyString);

代码示例来源:origin: JmStefanAndroid/PVCloudGroupn

if (response.isSuccessful()) {
  String resultStr = response.body().string();
  Log.e(TAG, "URL:"+response.request().httpUrl().url().toString()+" result=" + resultStr);
    if (response.request().httpUrl().url().toString().contains(Contants.API.BASE_URL)) {
      try {//尝试解析为基础数据
        BaseRespMsg respMsg = mGson.fromJson(resultStr, BaseRespMsg.class);

代码示例来源:origin: blockchain/api-v1-client-java

private String makeRequest(Request request) throws IOException {
 Response response = getOkHttpClientInstance().newCall(request).execute();
 if (isNotSuccessfulResponse(response))
   throw new IOException(String.format("Unsuccessful call to %s Response: %s",
       request.urlString(),
       response));
 return response.body().string();
}

代码示例来源:origin: fire3/sailorcast

public static String syncGet(String url) {
  Request request = buildRequest(url);
  Log.d("fire3", "sync request Url: " + request.urlString());
  try {
    Response response =  SailorCast.getHttpClient().newCall(request).execute();
    if (response.code() == 200) {
      String ret = new String(response.body().bytes(), "utf-8");
      return ret;
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}

代码示例来源:origin: org.graylog2/graylog2-radio

public void ping() throws IOException {
  final PingRequest pingRequest = PingRequest.create(ourUri.toString());
  final URI uri = serverUri.resolve("/system/radios/" + nodeId + "/ping");
  final Request request = new Request.Builder()
      .url(uri.toURL())
      .put(RequestBody.create(CONTENT_TYPE, objectMapper.writeValueAsBytes(pingRequest)))
      .build();
  final Response r = httpClient.newCall(request).execute();
  // fail on a non-ok status
  if (!r.isSuccessful()) {
    throw new RuntimeException("Expected successful HTTP response [2xx] but got [" + r.code() + "]. Request was " + request.urlString());
  }
}

代码示例来源:origin: spinnaker/kayenta

@Override
 public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
  return response.request().newBuilder().header("Proxy-Authorization", credential).build();
 }
});

代码示例来源:origin: pratamawijaya/example

@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()));

  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()));

  Timber.i("response : " + response.message());

  return response;
 }
}

代码示例来源:origin: zalando/logbook

@Override
public HttpRequest withBody() throws IOException {
  @Nullable final RequestBody body = request.body();
  if (body == null) {
    this.body = new byte[0];
  } else {
    final byte[] bytes = bytes(body);
    this.request = request.newBuilder()
        .method(request.method(), create(body.contentType(), bytes))
        .build();
    this.body = bytes;
  }
  return this;
}

代码示例来源:origin: zalando/logbook

static boolean canSkipBody(Response response) {
  if("HEAD".equals(response.request().method())) {
    return true;
  }
  return response.code() == HTTP_NO_CONTENT || response.code() == HTTP_NOT_MODIFIED;
}

相关文章