use of okhttp3.MediaType in project okhttputils by hongyangAndroid.
the class LoggerInterceptor method logForRequest.
private void logForRequest(Request request) {
try {
String url = request.url().toString();
Headers headers = request.headers();
Log.e(tag, "========request'log=======");
Log.e(tag, "method : " + request.method());
Log.e(tag, "url : " + url);
if (headers != null && headers.size() > 0) {
Log.e(tag, "headers : " + headers.toString());
}
RequestBody requestBody = request.body();
if (requestBody != null) {
MediaType mediaType = requestBody.contentType();
if (mediaType != null) {
Log.e(tag, "requestBody's contentType : " + mediaType.toString());
if (isText(mediaType)) {
Log.e(tag, "requestBody's content : " + bodyToString(request));
} else {
Log.e(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
}
}
}
Log.e(tag, "========request'log=======end");
} catch (Exception e) {
// e.printStackTrace();
}
}
use of okhttp3.MediaType in project azure-sdk-for-java by Azure.
the class BatchCredentialsInterceptor method signHeader.
private Request signHeader(Request request) throws IOException {
Request.Builder builder = request.newBuilder();
// Set Headers
if (request.headers().get("ocp-date") == null) {
DateTimeRfc1123 rfcDate = new DateTimeRfc1123(new DateTime());
builder.header("ocp-date", rfcDate.toString());
request = builder.build();
}
String signature = request.method() + "\n";
signature = signature + headerValue(request, "Content-Encoding") + "\n";
signature = signature + headerValue(request, "Content-Language") + "\n";
// Special handle content length
long length = -1;
if (request.body() != null) {
length = request.body().contentLength();
}
signature = signature + (length >= 0 ? Long.valueOf(length) : "") + "\n";
signature = signature + headerValue(request, "Content-MD5") + "\n";
// Special handle content type header
String contentType = request.header("Content-Type");
if (contentType == null) {
contentType = "";
if (request.body() != null) {
MediaType mediaType = request.body().contentType();
if (mediaType != null) {
contentType = mediaType.toString();
}
}
}
signature = signature + contentType + "\n";
signature = signature + headerValue(request, "Date") + "\n";
signature = signature + headerValue(request, "If-Modified-Since") + "\n";
signature = signature + headerValue(request, "If-Match") + "\n";
signature = signature + headerValue(request, "If-None-Match") + "\n";
signature = signature + headerValue(request, "If-Unmodified-Since") + "\n";
signature = signature + headerValue(request, "Range") + "\n";
ArrayList<String> customHeaders = new ArrayList<String>();
for (String name : request.headers().names()) {
if (name.toLowerCase().startsWith("ocp-")) {
customHeaders.add(name.toLowerCase());
}
}
Collections.sort(customHeaders);
for (String canonicalHeader : customHeaders) {
String value = request.header(canonicalHeader);
value = value.replace('\n', ' ').replace('\r', ' ').replaceAll("^[ ]+", "");
signature = signature + canonicalHeader + ":" + value + "\n";
}
signature = signature + "/" + credentials.accountName().toLowerCase() + "/" + request.url().uri().getPath().replaceAll("^[/]+", "");
// We temporary change client side auth code generator to bypass server
// bug 4092533
signature = signature.replace("%5C", "/").replace("%2F", "/");
String query = request.url().query();
if (query != null) {
Map<String, String> queryComponents = new TreeMap<String, String>();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8").toLowerCase(Locale.US);
queryComponents.put(key, key + ":" + URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
for (Map.Entry<String, String> entry : queryComponents.entrySet()) {
signature = signature + "\n" + entry.getValue();
}
}
String signedSignature = sign(credentials.keyValue(), signature);
String authorization = "SharedKey " + credentials.accountName() + ":" + signedSignature;
builder.header("Authorization", authorization);
return builder.build();
}
use of okhttp3.MediaType in project okhttp by square.
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.MediaType in project okhttp by square.
the class HttpOverHttp2Test method noDefaultContentLengthOnStreamingPost.
@Test
public void noDefaultContentLengthOnStreamingPost() throws Exception {
final byte[] postBytes = "FGHIJ".getBytes(Util.UTF_8);
server.enqueue(new MockResponse().setBody("ABCDE"));
Call call = client.newCall(new Request.Builder().url(server.url("/foo")).post(new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("text/plain; charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(postBytes);
}
}).build());
Response response = call.execute();
assertEquals("ABCDE", response.body().string());
RecordedRequest request = server.takeRequest();
assertEquals("POST /foo HTTP/1.1", request.getRequestLine());
assertArrayEquals(postBytes, request.getBody().readByteArray());
assertNull(request.getHeader("Content-Length"));
}
use of okhttp3.MediaType in project retrofit by square.
the class RequestBuilder method addHeader.
void addHeader(String name, String value) {
if ("Content-Type".equalsIgnoreCase(name)) {
MediaType type = MediaType.parse(value);
if (type == null) {
throw new IllegalArgumentException("Malformed content type: " + value);
}
contentType = type;
} else {
requestBuilder.addHeader(name, value);
}
}
Aggregations