use of okhttp3.MediaType in project retrofit by square.
the class RequestBuilder method build.
Request build() {
HttpUrl url;
HttpUrl.Builder urlBuilder = this.urlBuilder;
if (urlBuilder != null) {
url = urlBuilder.build();
} else {
// No query parameters triggered builder creation, just combine the relative URL and base URL.
// noinspection ConstantConditions Non-null if urlBuilder is null.
url = baseUrl.resolve(relativeUrl);
if (url == null) {
throw new IllegalArgumentException("Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl);
}
}
RequestBody body = this.body;
if (body == null) {
// Try to pull from one of the builders.
if (formBuilder != null) {
body = formBuilder.build();
} else if (multipartBuilder != null) {
body = multipartBuilder.build();
} else if (hasBody) {
// Body is absent, make an empty body.
body = RequestBody.create(null, new byte[0]);
}
}
MediaType contentType = this.contentType;
if (contentType != null) {
if (body != null) {
body = new ContentTypeOverridingRequestBody(body, contentType);
} else {
requestBuilder.addHeader("Content-Type", contentType.toString());
}
}
return requestBuilder.url(url).method(method, body).build();
}
use of okhttp3.MediaType in project MVPFrames by RockyQu.
the class TokenInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response originalResponse = chain.proceed(request);
/**
* 通过如下方法提前获取到请求完成的数据
*/
ResponseBody responseBody = originalResponse.body();
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);
}
String bodyString = buffer.clone().readString(charset);
Log.e("body---------->", bodyString);
// otherwise just pass the original response on
return originalResponse;
}
use of okhttp3.MediaType in project MVPFrames by RockyQu.
the class LoggingInterceptor 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);
}
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 (hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
log(requestStartMessage);
// Content-Type
if (hasRequestBody) {
if (requestBody.contentType() != null) {
log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
log("Content-Length: " + requestBody.contentLength());
}
}
// 拼装请求参数
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
log(name + ": " + headers.value(i));
}
}
// Request结束
if (!hasRequestBody) {
log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
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);
}
if (isPlaintext(buffer)) {
log(buffer.readString(charset));
log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
} else {
log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
}
}
// Response开始
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
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";
log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (", " + bodySize + " body") + ')');
headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
log(headers.name(i) + ": " + headers.value(i));
}
if (!HttpHeaders.hasBody(response)) {
log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
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) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
log("Couldn't decode the response body; charset is likely malformed.");
log("<-- END HTTP");
return response;
}
}
if (!isPlaintext(buffer)) {
log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
log(buffer.clone().readString(charset));
}
log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
return response;
}
use of okhttp3.MediaType in project MVPFrames by RockyQu.
the class NetworkInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不需要操作则返回参数中的request
if (handler != null) {
request = handler.onHttpRequest(chain, request);
}
NetworkStatusReceiver.Type type = NetworkStatusReceiver.getType(application);
if (type == NetworkStatusReceiver.Type.NONE) {
// 无网络时强制从缓存读取(必须得写,不然断网状态下,退出应用,或者等待一分钟后,会获取不到缓存)
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response originalResponse = chain.proceed(request);
if (type == NetworkStatusReceiver.Type.MOBILE || type == NetworkStatusReceiver.Type.WIFI) {
// 0秒
int maxAge = 0;
originalResponse = originalResponse.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, max-age=" + maxAge).build();
} else {
// 1小时
int maxTime = 60 * 60;
originalResponse = originalResponse.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, only-if-cached, max-stale=" + maxTime).build();
}
// 读取服务器返回的结果
ResponseBody responseBody = originalResponse.body();
BufferedSource source = responseBody.source();
// Buffer the entire body.
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
// 获取content的压缩类型
String encoding = originalResponse.headers().get("Content-Encoding");
Buffer clone = buffer.clone();
String bodyString;
// 解析response content
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
// content使用gzip压缩
bodyString = ZipUtils.decompressForGzip(clone.readByteArray());
} else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
// content使用zlib压缩
bodyString = ZipUtils.decompressToStringForZlib(clone.readByteArray());
} else {
// content没有被压缩
Charset charset = Charset.forName("UTF-8");
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(charset);
}
bodyString = clone.readString(charset);
}
// 这里可以提前一步拿到服务器返回的结果,外部实现此接口可以做一些操作,比如Token超时,重新获取
if (handler != null) {
return handler.onHttpResponse(bodyString, chain, request, originalResponse);
}
return originalResponse;
}
use of okhttp3.MediaType in project AndoridLib by twp520.
the class HttpLogInterceptor method logForRequest.
private void logForRequest(Request request) {
try {
String url = request.url().toString();
Log.e(tag, "========请求日志开始=======");
Log.e(tag, "请求方式 : " + request.method());
Log.e(tag, "url : " + url);
RequestBody requestBody = request.body();
if (requestBody != null) {
MediaType mediaType = requestBody.contentType();
if (mediaType != null) {
Log.e(tag, "请求内容类别 : " + mediaType.toString());
if (isText(mediaType)) {
Log.e(tag, "请求内容 : " + bodyToString(request));
} else {
Log.e(tag, "请求内容 : " + " 无法识别。");
}
}
}
Log.e(tag, "========请求日志结束=======");
} catch (Exception e) {
// e.printStackTrace();
}
}
Aggregations