List of usage examples for com.squareup.okhttp Request body
RequestBody body
To view the source code for com.squareup.okhttp Request body.
Click Source Link
From source file:io.jawg.osmcontributor.rest.utils.AuthenticationRequestInterceptor.java
License:Open Source License
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Map<String, String> oAuthParams = loginPreferences.retrieveOAuthParams(); if (oAuthParams != null) { Request originalRequest = response.request(); String requestUrl = originalRequest.urlString(); OAuthRequest oAuthRequest = new OAuthRequest(oAuthParams.get(CONSUMER_PARAM), oAuthParams.get(CONSUMER_SECRET_PARAM)); oAuthRequest/*from w w w. j a va 2 s .co m*/ .initParam(OAuthParams.getOAuthParams().put(TOKEN_PARAM, oAuthParams.get(TOKEN_PARAM)).toMap()); oAuthRequest.setOAuthToken(oAuthParams.get(TOKEN_PARAM)); oAuthRequest.setOAuthTokenSecret(oAuthParams.get(TOKEN_SECRET_PARAM)); oAuthRequest.setRequestUrl(requestUrl); oAuthRequest.signRequest(Verb.valueOf(originalRequest.method())); oAuthRequest.encodeParams(); Request.Builder finalRequest = originalRequest.newBuilder().header("Accept", "text/xml") .header("Authorization", oAuthRequest.getOAuthHeader()) .method(originalRequest.method(), originalRequest.body()); return finalRequest.build(); } else { // create Base64 encoded string String authorization = "Basic " + Base64.encodeToString( (loginPreferences.retrieveLogin() + ":" + loginPreferences.retrievePassword()).getBytes(), Base64.NO_WRAP); return response.request().newBuilder().header("Authorization", authorization) .header("Accept", "text/xml").build(); } }
From source file:io.macgyver.core.okhttp.LoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE || (!slf4j.isDebugEnabled())) { return chain.proceed(request); }//from w w w . j a v a 2 s. c o m boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; try { RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. 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 (name.equalsIgnoreCase("authorization")) { log(name + ": ************"); } else { // Skip headers from the request body as they are // explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { log(name + ": " + headers.value(i)); } } } if (!logBody || !hasRequestBody) { slf4j.debug("--> 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) { contentType.charset(UTF8); } log(""); String body = redactRequestBody(buffer.readString(charset)); log(body); log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace } long startNs = System.nanoTime(); Response response = chain.proceed(request); try { 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" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { log("<-- END HTTP"); } else if (!isResponseBodyPrintable(response)) { log("<-- END HTTP (body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(maxPrintableBodySize); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() != 0) { log(""); log(redactResponseBody(buffer.clone().readString(charset))); } log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString()); } return response; }
From source file:it.smartcommunitylab.GzipRequestInterceptor.java
License:Apache License
@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); }/*from w w w .j av a 2 s . c o m*/ Request compressedRequest = originalRequest.newBuilder().header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))).build(); return chain.proceed(compressedRequest); }
From source file:me.touko.okhttp2.util.RequestBodyUtil.java
License:Apache License
public static byte[] readBody(Request request) throws IOException { if (!hasRequestBody(request)) { return new byte[0]; } else {/* ww w .j ava 2s . c om*/ final Request copy = request.newBuilder().build(); final Buffer buffer = new Buffer(); copy.body().writeTo(buffer); return buffer.readByteArray(); } }
From source file:me.touko.okhttp2.util.RequestBodyUtil.java
License:Apache License
public static boolean hasRequestBody(Request request) { try {//from w w w .java 2 s . c o m return request.body() != null && request.body().contentLength() > 0; } catch (IOException e) { return false; } }
From source file:mobi.lab.sample_event_logging_library.service.LogPostService.java
License:Open Source License
@Override public void onCreate() { super.onCreate(); //TODO: starting from Android 5.0 we could use JobScheduler (currently not in support libraries) handler = new Handler(); handler.postDelayed(timedRunnable, Config.MAX_TIME_INTERVAL_BETWEEN_REQUESTS); logEventsForRequest = new ArrayList<>(); OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override/*from w w w .j a v a 2s .c o m*/ public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.d(TAG, String.format("\n\nrequest:%s\nheaders:%s\n" + "url:%s", request.body().toString(), request.headers(), request.httpUrl().toString())); return chain.proceed(request); } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(Network.BASE_API_URL) .addConverterFactory(GsonConverterFactory.create()).client(client).build(); logEventService = retrofit.create(LogEventRequest.class); if (checkCallingOrSelfPermission( Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkCallingOrSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //TODO: ask for permission if not given Log.d(TAG, "location permission not granted"); isLocationServicesEnabled = false; return; } isLocationServicesEnabled = true; final LocationManager locationManager = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE); final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); Log.d(TAG, "requesting user location"); locationManager.requestLocationUpdates(Config.LOCATION_UPDATES_MIN_TIME, Config.LOCATION_UPDATES_MIN_DISTANCE, criteria, this, null); }
From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }//from ww w .j ava2 s . c om boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; UUID requestId = UUID.randomUUID(); StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n') .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol); if (!logHeaders && requestBody != null) { requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)"); } requestMessage.append('\n'); if (logHeaders) { if (requestBody != null) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n'); } if (requestBody.contentLength() != -1) { requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n'); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name) || "Proxy-Authorization".equalsIgnoreCase(name) || "WWW-Authenticate".equalsIgnoreCase(name)) { requestMessage.append(name).append(": *****\n"); } // Skip headers from the request body as they are explicitly // logged above. else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { requestMessage.append(name).append(": ").append(headers.value(i)).append('\n'); } } if (!logBody || requestBody == null) { requestMessage.append("--> END ").append(requestId).append('\n'); } else if (bodyEncoded(request.headers())) { requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n'); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } requestMessage.append('\n'); if (isPlaintext(buffer)) { requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId) .append(" (").append(requestBody.contentLength()).append("-byte body)\n"); } else { requestMessage.append("--> END ").append(requestId).append(" (binary ") .append(requestBody.contentLength()).append("-byte body omitted)\n"); } } } logger.log(requestMessage.substring(0, requestMessage.length() - 1)); long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- " + requestId + "HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ') .append(response.request().url()).append(" (").append(tookMs).append("ms"); if (!logHeaders) { responseMessage.append(", "); if (contentLength != -1) { responseMessage.append(contentLength).append("-byte"); } else { responseMessage.append("unknown-length"); } responseMessage.append(" body"); } responseMessage.append(")\n"); responseMessage.append(response.code()).append(' ').append(response.message()).append('\n'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n'); } if (!logBody || !HttpEngine.hasBody(response)) { responseMessage.append("<-- END HTTP\n"); } else if (bodyEncoded(response.headers())) { responseMessage.append("<-- END HTTP (encoded body omitted)\n"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (!isPlaintext(buffer)) { responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size()) .append("-byte body omitted)"); logger.log(responseMessage.toString()); return response; } if (contentLength != 0) { responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n'); } responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n"); } } logger.log(responseMessage.substring(0, responseMessage.length() - 1)); return response; }
From source file:net.qiujuer.common.okhttp.core.HttpCore.java
License:Apache License
protected void deliveryAsyncResult(final Request request, final StreamCall call, final HttpCallback<?> callback) { Util.log("onDelivery:" + request.url().toString()); final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback; //Call start//w w w . j a va 2s . c om callStart(resCallBack, request); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { Util.log("onFailure:" + request.toString()); callFailure(resCallBack, request, null, e); callFinish(resCallBack); } @Override public void onResponse(final Response response) { OutputStream out = call.getOutputStream(); InputStream in = null; byte[] buf = new byte[mBufferSize]; try { Util.log("onResponse:Code:%d Stream.", response.code()); ResponseBody body = response.body(); bindResponseProgressCallback(request.body(), body, callback); in = body.byteStream(); int size; while ((size = in.read(buf)) != -1) { out.write(buf, 0, size); out.flush(); } // On success call.onSuccess(response.code()); } catch (Exception e) { Util.log("onResponse Failure:" + response.request().toString()); callFailure(resCallBack, response.request(), response, e); } finally { com.squareup.okhttp.internal.Util.closeQuietly(in); com.squareup.okhttp.internal.Util.closeQuietly(out); } callFinish(resCallBack); } }); }
From source file:net.qiujuer.common.okhttp.core.HttpCore.java
License:Apache License
public final <T> T uploadSync(Class<T> tClass, Request.Builder builder, Object tag, HttpCallback<T> callback) { setTag(builder, tag);//from w w w . ja v a2 s . co m Request request = builder.build(); if (callback != null) { RequestBody requestBody = request.body(); if (requestBody instanceof ForwardRequestBody) { ((ForwardRequestBody) (requestBody)).setListener(callback); } } return sync(tClass, request, callback); }
From source file:net.qiujuer.common.okhttp.core.HttpCore.java
License:Apache License
public final void uploadAsync(Request.Builder builder, Object tag, HttpCallback callback) { setTag(builder, tag);/*from www. java2s . c o m*/ Request request = builder.build(); if (callback != null) { RequestBody requestBody = request.body(); if (requestBody instanceof ForwardRequestBody) { ((ForwardRequestBody) (requestBody)).setListener(callback); } } async(request, callback); }