use of okhttp3.RequestBody in project okhttp by square.
the class OkHttpURLConnection method getResponse.
/**
* Aggressively tries to get the final HTTP response, potentially making many HTTP requests in the
* process in order to cope with redirects and authentication.
*/
private Response getResponse(boolean networkResponseOnError) throws IOException {
synchronized (lock) {
if (response != null)
return response;
if (callFailure != null) {
if (networkResponseOnError && networkResponse != null)
return networkResponse;
throw propagate(callFailure);
}
}
Call call = buildCall();
networkInterceptor.proceed();
OutputStreamRequestBody requestBody = (OutputStreamRequestBody) call.request().body();
if (requestBody != null)
requestBody.outputStream().close();
if (executed) {
synchronized (lock) {
try {
while (response == null && callFailure == null) {
// Wait until the response is returned or the call fails.
lock.wait();
}
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
} else {
executed = true;
try {
onResponse(call, call.execute());
} catch (IOException e) {
onFailure(call, e);
}
}
synchronized (lock) {
if (callFailure != null)
throw propagate(callFailure);
if (response != null)
return response;
}
throw new AssertionError();
}
use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.
the class GzipRequestInterceptor method forceContentLength.
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.
the class GzipRequestInterceptor method gzip.
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public long contentLength() {
// We don't know the compressed length in advance!
return -1;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.
the class HttpLoggingInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
boolean logBody = level == Level.BODY;
boolean logHeaders = logBody || level == Level.HEADERS;
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
logger.log(requestStartMessage);
if (logHeaders) {
if (hasRequestBody) {
// them to be included (when available) so there values are known.
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
}
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
logger.log(name + ": " + headers.value(i));
}
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
logger.log("");
if (isPlaintext(buffer)) {
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
} else {
logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
}
}
}
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
logger.log("<-- HTTP FAILED: " + e);
throw e;
}
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
if (logHeaders) {
Headers headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.name(i) + ": " + headers.value(i));
}
if (!logBody || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
if (!isPlaintext(buffer)) {
logger.log("");
logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
logger.log("");
logger.log(buffer.clone().readString(charset));
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
}
return response;
}
use of okhttp3.RequestBody in project Fast-Android-Networking by amitshekhariitbhu.
the class InternalNetworking method performSimpleRequest.
public static Response performSimpleRequest(ANRequest request) throws ANError {
Request okHttpRequest;
Response okHttpResponse;
try {
Request.Builder builder = new Request.Builder().url(request.getUrl());
addHeadersToRequestBuilder(builder, request);
RequestBody requestBody = null;
switch(request.getMethod()) {
case GET:
{
builder = builder.get();
break;
}
case POST:
{
requestBody = request.getRequestBody();
builder = builder.post(requestBody);
break;
}
case PUT:
{
requestBody = request.getRequestBody();
builder = builder.put(requestBody);
break;
}
case DELETE:
{
requestBody = request.getRequestBody();
builder = builder.delete(requestBody);
break;
}
case HEAD:
{
builder = builder.head();
break;
}
case PATCH:
{
requestBody = request.getRequestBody();
builder = builder.patch(requestBody);
break;
}
}
if (request.getCacheControl() != null) {
builder.cacheControl(request.getCacheControl());
}
okHttpRequest = builder.build();
if (request.getOkHttpClient() != null) {
request.setCall(request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).build().newCall(okHttpRequest));
} else {
request.setCall(sHttpClient.newCall(okHttpRequest));
}
final long startTime = System.currentTimeMillis();
final long startBytes = TrafficStats.getTotalRxBytes();
okHttpResponse = request.getCall().execute();
final long timeTaken = System.currentTimeMillis() - startTime;
if (okHttpResponse.cacheResponse() == null) {
final long finalBytes = TrafficStats.getTotalRxBytes();
final long diffBytes;
if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
diffBytes = okHttpResponse.body().contentLength();
} else {
diffBytes = finalBytes - startBytes;
}
ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, okHttpResponse.body().contentLength(), false);
} else if (request.getAnalyticsListener() != null) {
if (okHttpResponse.networkResponse() == null) {
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, 0, 0, true);
} else {
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, (requestBody != null && requestBody.contentLength() != 0) ? requestBody.contentLength() : -1, 0, true);
}
}
} catch (IOException ioe) {
throw new ANError(ioe);
}
return okHttpResponse;
}
Aggregations