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:alberto.avengers.model.rest.utils.interceptors.HttpLoggingInterceptor.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 w ww.j a v a2 s . c o m 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.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } String endMessage = "--> END " + request.method(); if (logBody && hasRequestBody) { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } logger.log(""); logger.log(buffer.readString(charset)); endMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(endMessage); } long startNs = System.nanoTime(); Response response = chain.proceed(request); long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); logger.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++) { logger.log(headers.name(i) + ": " + headers.value(i)); } String endMessage = "<-- END HTTP"; if (logBody) { 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 (responseBody.contentLength() != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } endMessage += " (" + buffer.size() + "-byte body)"; } logger.log(endMessage); } return response; }
From source file:at.bitfire.dav4android.BasicDigestAuthenticator.java
License:Open Source License
protected Request authorizationRequest(Request request, HttpUtils.AuthScheme digest) { String realm = digest.params.get("realm"), opaque = digest.params.get("opaque"), nonce = digest.params.get("nonce"); Algorithm algorithm = Algorithm.determine(digest.params.get("algorithm")); Protection qop = Protection.selectFrom(digest.params.get("qop")); // build response parameters String response = null;//w w w.j av a2 s . co m List<String> params = new LinkedList<>(); params.add("username=" + quotedString(username)); if (realm != null) params.add("realm=" + quotedString(realm)); else return null; if (nonce != null) params.add("nonce=" + quotedString(nonce)); else return null; if (opaque != null) params.add("opaque=" + quotedString(opaque)); else return null; if (algorithm != null) params.add("algorithm=" + quotedString(algorithm.name)); final String method = request.method(); final String digestURI = request.httpUrl().encodedPath(); params.add("uri=" + quotedString(digestURI)); if (qop != null) { params.add("qop=" + qop.name); params.add("cnonce=" + quotedString(clientNonce)); int nc = nonceCount.getAndIncrement(); String ncValue = String.format("%08x", nc); params.add("nc=" + ncValue); String a1 = null; if (algorithm == Algorithm.MD5) a1 = username + ":" + realm + ":" + password; else if (algorithm == Algorithm.MD5_SESSION) a1 = h(username + ":" + realm + ":" + password) + ":" + nonce + ":" + clientNonce; //Constants.log.trace("A1=" + a1); String a2 = null; if (qop == Protection.Auth) a2 = method + ":" + digestURI; else if (qop == Protection.AuthInt) try { RequestBody body = request.body(); a2 = method + ":" + digestURI + ":" + (body != null ? h(body) : h("")); } catch (IOException e) { Constants.log.warn("Couldn't get entity-body for hash calculation"); } //Constants.log.trace("A2=" + a2); if (a1 != null && a2 != null) response = kd(h(a1), nonce + ":" + ncValue + ":" + clientNonce + ":" + qop.name + ":" + h(a2)); } else { //Constants.log.debug("Using legacy Digest auth"); // legacy (backwards compatibility with RFC 2069) if (algorithm == Algorithm.MD5) { String a1 = username + ":" + realm + ":" + password, a2 = method + ":" + digestURI; response = kd(h(a1), nonce + ":" + h(a2)); } } if (response != null) { params.add("response=" + quotedString(response)); return request.newBuilder().header(HEADER_AUTHORIZATION, "Digest " + TextUtils.join(", ", params)) .build(); } else return null; }
From source file:at.bitfire.dav4android.exception.HttpException.java
License:Open Source License
public HttpException(Response response) { super(response.code() + " " + response.message()); status = response.code();//from w ww . j ava 2 s . com message = response.message(); /* As we don't know the media type and character set of request and response body, only printable ASCII characters will be shown in clear text. Other octets will be shown as "[xx]" where xx is the hex value of the octet. */ // format request Request request = response.request(); StringBuilder formatted = new StringBuilder(); formatted.append(request.method() + " " + request.urlString() + "\n"); Headers headers = request.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (request.body() != null) try { formatted.append("\n"); Buffer buffer = new Buffer(); request.body().writeTo(buffer); while (!buffer.exhausted()) appendByte(formatted, buffer.readByte()); } catch (IOException e) { } this.request = formatted.toString(); // format response formatted = new StringBuilder(); formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n"); headers = response.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (response.body() != null) try { formatted.append("\n"); for (byte b : response.body().bytes()) appendByte(formatted, b); } catch (IOException e) { } this.response = formatted.toString(); }
From source file:bitrefill.retrofit.Generator.java
static void configAuth(OkHttpClient client, Config config) { final String auth = getAuth(config); if (auth == null) { return;/*ww w. jav a2 s .com*/ } client.interceptors().clear(); client.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Basic " + auth) .header("Accept", "applicaton/json").method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }); }
From source file:cn.com.canon.darwin.modules.service.api.interceptor.HttpLoggingInterceptor.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 w w w.jav a 2s . c o m 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.getProtocol() : 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) { // // 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) { // 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 || !HttpEngine.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { logger.log("<-- END HTTP (encoded body omitted)"); } 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) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logger.log(""); logger.log("Couldn't decode the response body; charset is likely malformed."); logger.log("<-- END HTTP"); return response; } } 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; }
From source file:co.paralleluniverse.fibers.okhttp.InterceptorTest.java
License:Open Source License
private void rewriteRequestToServer(List<Interceptor> interceptors) throws Exception { server.enqueue(new MockResponse()); interceptors.add(new Interceptor() { @Override/*from w w w. ja va 2 s .co m*/ public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body())) .addHeader("OkHttp-Intercepted", "yep").build()); } }); Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Original-Header", "foo") .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build(); FiberOkHttpUtil.executeInFiber(client, request); RecordedRequest recordedRequest = server.takeRequest(); assertEquals("ABC", recordedRequest.getBody().readUtf8()); assertEquals("foo", recordedRequest.getHeader("Original-Header")); assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted")); assertEquals("POST", recordedRequest.getMethod()); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
private void rewriteRequestToServer(List<Interceptor> interceptors) throws Exception { server.enqueue(new MockResponse()); interceptors.add(new Interceptor() { @Override//from w w w. jav a2 s.com public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); return chain.proceed(originalRequest.newBuilder().method("POST", uppercase(originalRequest.body())) .addHeader("OkHttp-Intercepted", "yep").build()); } }); Request request = new Request.Builder().url(server.url("/")).addHeader("Original-Header", "foo") .method("PUT", RequestBody.create(MediaType.parse("text/plain"), "abc")).build(); client.newCall(request).execute(); RecordedRequest recordedRequest = server.takeRequest(); assertEquals("ABC", recordedRequest.getBody().readUtf8()); assertEquals("foo", recordedRequest.getHeader("Original-Header")); assertEquals("yep", recordedRequest.getHeader("OkHttp-Intercepted")); assertEquals("POST", recordedRequest.getMethod()); }
From source file:com.afrisoftech.funsoft.mobilepay.MobilePayAPI.java
public void sendPaymentRequest(String accessToken) { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); String message = null;/*from ww w . j av a 2 s . c o m*/ JSONObject json = new JSONObject(); try { json.put("InitiatorName", "Charles Waweru"); json.put("SecurityCredential", this.encryptInitiatorPassword("cert.cer", "3414")); json.put("CommandID", "CustomerPayBillOnline"); json.put("Amount", "10"); json.put("PartyA", "254714433693"); json.put("PartyB", "881100"); json.put("Remarks", "Testing Rest API"); json.put("QueueTimeOutURL", ""); json.put("ResultURL", "https://192.162.85.226:17933/FunsoftWebServices/funsoft/InvoiceService/mpesasettlement"); json.put("Occasion", "1234567891"); message = json.toString(); System.out.println("This is the JSON String : " + message); } catch (JSONException ex) { Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex); } RequestBody body = RequestBody.create(mediaType, message); Request request = new Request.Builder().url("https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest") .post(body).addHeader("authorization", "Bearer " + accessToken) .addHeader("content-type", "application/json").build(); try { System.out.println("Request Build Security Credentials : [" + this.encryptInitiatorPassword("cert.cer", "3414") + "]"); System.out.println("Request Build : [" + request.body().toString() + "]"); Response response = client.newCall(request).execute(); JSONObject myObject = null; try { myObject = new JSONObject(response.body().string()); } catch (JSONException ex) { Logger.getLogger(MobilePayAPI.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Payment Request Response : " + myObject.toString()); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.brq.wallet.external.glidera.api.GlideraService.java
private GlideraService(@NonNull final NetworkParameters networkParameters) { Preconditions.checkNotNull(networkParameters); this.networkParameters = networkParameters; this.baseUrl = getBaseUrl(networkParameters); if (networkParameters.isTestnet()) { clientId = TESTNET_CLIENT_ID;//from w ww. j av a2s . c om } else { clientId = MAINNET_CLIENT_ID; } /** * The Sha256 HMAC hash of the message. Use the secret matching the access_key to hash the message. * The message is the concatenation of the X-ACCESS-NONCE + URI of the request + message body JSON. * The final X-ACCESS-SIGNATURE is the HmacSha256 of the UTF-8 encoding of the message as a Hex encoded string */ final Interceptor apiCredentialInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (_oAuth1Response != null) { Request.Builder requestBuilder = request.newBuilder(); synchronized (_nonce) { final String nonce = _nonce.getNonceString(); final String uri = request.urlString(); String message = nonce + uri; if (request.body() != null && request.body().contentLength() > 0) { Buffer bodyBuffer = new Buffer(); request.body().writeTo(bodyBuffer); byte[] bodyBytes = bodyBuffer.readByteArray(); String body = new String(bodyBytes, Charsets.UTF_8); message += body; } final byte[] messageBytes = message.getBytes(Charsets.UTF_8); final byte[] secretBytes = _oAuth1Response.getSecret().getBytes(Charsets.UTF_8); final byte[] signatureBytes = Hmac.hmacSha256(secretBytes, messageBytes); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Hex.encode(signatureBytes, stream); final String signature = stream.toString(); request = requestBuilder.header(HEADER_ACCESS_KEY, _oAuth1Response.getAccess_key()) .header(HEADER_ACCESS_NONCE, nonce).header(HEADER_ACCESS_SIGNATURE, signature) .build(); } } return chain.proceed(request); } }; OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(15000, TimeUnit.MILLISECONDS); client.setReadTimeout(15000, TimeUnit.MILLISECONDS); client.networkInterceptors().add(apiCredentialInterceptor); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.); objectMapper.registerModule(new WapiJsonModule()); /* We should always add client_id to the header */ RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { requestFacade.addHeader(HEADER_CLIENT_ID, clientId); } }; /* Create the json adapter */ RestAdapter adapter = new RestAdapter.Builder().setEndpoint(baseUrl + "/api/" + API_VERSION + "/") //.setLogLevel(RestAdapter.LogLevel.FULL) .setLogLevel(RestAdapter.LogLevel.BASIC).setLog(new AndroidLog("Glidera")) .setConverter(new JacksonConverter(objectMapper)).setClient(new NullBodyAwareOkClient(client)) .setRequestInterceptor(requestInterceptor).build(); glideraApi = adapter.create(GlideraApi.class); }
From source file:com.carlospinan.demoretrofit2.helpers.LoggingInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Log.d(LOG_TAG, String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));/*from w w w.ja v a 2s .com*/ Buffer requestBuffer = new Buffer(); if (request.body() != null) { request.body().writeTo(requestBuffer); Log.d(LOG_TAG, requestBuffer.readUtf8()); } Response response = chain.proceed(request); long t2 = System.nanoTime(); Log.d(LOG_TAG, String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); MediaType contentType = response.body().contentType(); String content = response.body().string(); Log.d(LOG_TAG, content); ResponseBody wrappedBody = ResponseBody.create(contentType, content); return response.newBuilder().body(wrappedBody).build(); }