Java Code Examples for com.squareup.okhttp.Response#body()

The following examples show how to use com.squareup.okhttp.Response#body() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZalyHttpClient.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 2
Source File: ZalyHttpClient.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 3
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 4
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 5
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 6
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 7
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 8
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 9
Source File: HttpUtil.java    From AutoEx with Apache License 2.0 6 votes vote down vote up
public static void dogetHttp3(final String urls, final HResponse mHResponse) {
    try {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
        Request build1 = new Request.Builder().url(urls).get().build();

        Response execute = client.newCall(build1).execute();
        if (execute == null || execute.body() == null) {
            mHResponse.onError("没有找到任何可参考的,真可惜。");
            return;
        }
        String string = execute.body().string();
        mHResponse.onFinish(string);
    } catch (IOException e) {
        e.printStackTrace();
        mHResponse.onError(e.getMessage());
    }
}
 
Example 10
Source File: ZalyHttpClient.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example 11
Source File: HttpApiBase.java    From iview-android-tv with MIT License 6 votes vote down vote up
private ResponseBody fetchFromNetwork(Uri url, int staleness) {
    Request.Builder builder = new Request.Builder();
    builder.url(url.toString());
    if (staleness > 0) {
        builder.cacheControl(allowStaleCache(staleness));
    }
    Request request = builder.build();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(60, TimeUnit.SECONDS);
    Log.d(TAG, "Requesting URL:" + request.urlString());
    try {
        Response response = client.newCall(request).execute();
        if (response.cacheResponse() != null) {
            Log.d(TAG, "Cached response [" + response.code() + "]:" + request.urlString());
        } else {
            Log.d(TAG, "Network response [" + response.code() + "]:" + request.urlString());
        }
        if (response.isSuccessful()) {
            return response.body();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 12
Source File: OkHttpStreamFetcher.java    From android-tutorials-glide with MIT License 6 votes vote down vote up
@Override
public InputStream loadData(Priority priority) throws Exception {
    Request.Builder requestBuilder = new Request.Builder()
            .url(url.toStringUrl());

    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }

    Request request = requestBuilder.build();

    Response response = client.newCall(request).execute();
    responseBody = response.body();
    if (!response.isSuccessful()) {
        throw new IOException("Request failed with code: " + response.code());
    }

    long contentLength = responseBody.contentLength();
    stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
    return stream;
}
 
Example 13
Source File: SimpleRequest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@Override
public void onResponse(Response response) {
    if (!response.isSuccessful()) {
        postOnFailure(parseUnsuccessfulResponse(response));
        return;
    }

    ResponseBody body = response.body();
    try {
        Reader charStream = body.charStream();
        T payload = getAdapter().fromJson(charStream);
        postOnSuccess(payload);
    } catch (IOException e) {
        final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e);
        postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception));
    } finally {
        closeStream(body);
    }
}
 
Example 14
Source File: AllureOkHttp.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(final Chain chain) throws IOException {
    final AttachmentProcessor<AttachmentData> processor = new DefaultAttachmentProcessor();

    final Request request = chain.request();
    final String requestUrl = request.url().toString();
    final HttpRequestAttachment.Builder requestAttachmentBuilder = HttpRequestAttachment.Builder
            .create("Request", requestUrl)
            .setMethod(request.method())
            .setHeaders(toMapConverter(request.headers().toMultimap()));

    final RequestBody requestBody = request.body();
    if (Objects.nonNull(requestBody)) {
        requestAttachmentBuilder.setBody(readRequestBody(requestBody));
    }
    final HttpRequestAttachment requestAttachment = requestAttachmentBuilder.build();
    processor.addAttachment(requestAttachment, new FreemarkerAttachmentRenderer(requestTemplatePath));

    final Response response = chain.proceed(request);
    final HttpResponseAttachment.Builder responseAttachmentBuilder = HttpResponseAttachment.Builder
            .create("Response")
            .setResponseCode(response.code())
            .setHeaders(toMapConverter(response.headers().toMultimap()));

    final Response.Builder responseBuilder = response.newBuilder();

    final ResponseBody responseBody = response.body();

    if (Objects.nonNull(responseBody)) {
        final byte[] bytes = responseBody.bytes();
        responseAttachmentBuilder.setBody(new String(bytes, StandardCharsets.UTF_8));
        responseBuilder.body(ResponseBody.create(responseBody.contentType(), bytes));
    }

    final HttpResponseAttachment responseAttachment = responseAttachmentBuilder.build();
    processor.addAttachment(responseAttachment, new FreemarkerAttachmentRenderer(responseTemplatePath));

    return responseBuilder.build();
}
 
Example 15
Source File: OkHttpStack.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}
 
Example 16
Source File: ApiClient.java    From ariADDna with Apache License 2.0 5 votes vote down vote up
/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type
 * @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 {
    LOGGER.info("Method {handleResponse} was called with response code: {}, returnType is {}",
            response.code(), returnType == null ? null : returnType.getTypeName());
    if (response.isSuccessful()) {
        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) {
                LOGGER.error(
                        "Method {handleResponse} was called, response code: {}, exception: {}",
                        response.code(), e.getStackTrace());
                throw new ApiException(response.message(), e, response.code(),
                        response.headers().toMultimap());
            }
        }
        LOGGER.error(
                "Method {handleResponse} was called, response.body() == null, response.code = {}, response.message() = {}, response.headers() = {}",
                response.code(), response.message(), response.headers().toMultimap());
        throw new ApiException(response.message(), response.code(),
                response.headers().toMultimap(), respBody);
    }
}
 
Example 17
Source File: OkHttpStack.java    From wasp with Apache License 2.0 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException {
  BasicHttpEntity entity = new BasicHttpEntity();
  ResponseBody body = response.body();

  entity.setContent(body.byteStream());
  entity.setContentLength(body.contentLength());
  entity.setContentEncoding(response.header("Content-Encoding"));

  if (body.contentType() != null) {
    entity.setContentType(body.contentType().type());
  }
  return entity;
}
 
Example 18
Source File: StethoInterceptor.java    From stetho with MIT License 4 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
  String requestId = mEventReporter.nextRequestId();

  Request request = chain.request();

  RequestBodyHelper requestBodyHelper = null;
  if (mEventReporter.isEnabled()) {
    requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
    OkHttpInspectorRequest inspectorRequest =
        new OkHttpInspectorRequest(requestId, request, requestBodyHelper);
    mEventReporter.requestWillBeSent(inspectorRequest);
  }

  Response response;
  try {
    response = chain.proceed(request);
  } catch (IOException e) {
    if (mEventReporter.isEnabled()) {
      mEventReporter.httpExchangeFailed(requestId, e.toString());
    }
    throw e;
  }

  if (mEventReporter.isEnabled()) {
    if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
      requestBodyHelper.reportDataSent();
    }

    Connection connection = chain.connection();
    if (connection == null) {
      throw new IllegalStateException(
          "No connection associated with this request; " +
              "did you use addInterceptor instead of addNetworkInterceptor?");
    }
    mEventReporter.responseHeadersReceived(
        new OkHttpInspectorResponse(
            requestId,
            request,
            response,
            connection));

    ResponseBody body = response.body();
    MediaType contentType = null;
    InputStream responseStream = null;
    if (body != null) {
      contentType = body.contentType();
      responseStream = body.byteStream();
    }

    responseStream = mEventReporter.interpretResponseStream(
        requestId,
        contentType != null ? contentType.toString() : null,
        response.header("Content-Encoding"),
        responseStream,
        new DefaultResponseHandler(mEventReporter, requestId));
    if (responseStream != null) {
      response = response.newBuilder()
          .body(new ForwardingResponseBody(body, responseStream))
          .build();
    }
  }

  return response;
}
 
Example 19
Source File: OkHttpInterceptor.java    From weex with Apache License 2.0 4 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
  String requestId = String.valueOf(mNextRequestId.getAndIncrement());

  Request request = chain.request();

  RequestBodyHelper requestBodyHelper = null;
  if (mEventReporter.isEnabled()) {
    requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
    OkHttpInspectorRequest inspectorRequest =
        new OkHttpInspectorRequest(requestId, request, requestBodyHelper);
    mEventReporter.requestWillBeSent(inspectorRequest);
  }

  Response response;
  try {
    response = chain.proceed(request);
  } catch (IOException e) {
    if (mEventReporter.isEnabled()) {
      mEventReporter.httpExchangeFailed(requestId, e.toString());
    }
    throw e;
  }

  if (mEventReporter.isEnabled()) {
    if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
      requestBodyHelper.reportDataSent();
    }

    Connection connection = chain.connection();
    mEventReporter.responseHeadersReceived(
        new OkHttpInspectorResponse(
            requestId,
            request,
            response,
            connection));

    ResponseBody body = response.body();
    MediaType contentType = null;
    InputStream responseStream = null;
    if (body != null) {
      contentType = body.contentType();
      responseStream = body.byteStream();
    }

    responseStream = mEventReporter.interpretResponseStream(
        requestId,
        contentType != null ? contentType.toString() : null,
        response.header("Content-Encoding"),
        responseStream,
        new DefaultResponseHandler(mEventReporter, requestId));
    if (responseStream != null) {
      response = response.newBuilder()
          .body(new ForwardingResponseBody(body, responseStream))
          .build();
    }
  }

  return response;
}
 
Example 20
Source File: HttpClient.java    From zsync4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static InputStream inputStream(Response response, ResourceTransferListener<Response> listener) throws IOException {
  final ResponseBody body = response.body();
  final InputStream in = body.byteStream();
  return new ObservableResourceInputStream<>(in, listener, response, response.body().contentLength());
}