List of usage examples for com.squareup.okhttp MediaType toString
@Override
public String toString()
From source file:at.bitfire.dav4android.property.GetContentType.java
License:Open Source License
public GetContentType(MediaType mediaType) { type = mediaType.toString(); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
@Test public void networkInterceptorsCanChangeRequestMethodFromGetToPost() throws Exception { server.enqueue(new MockResponse()); client.networkInterceptors().add(new Interceptor() { @Override/*from ww w. j a v a2 s. co m*/ public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = RequestBody.create(mediaType, "abc"); return chain.proceed(originalRequest.newBuilder().method("POST", body) .header("Content-Type", mediaType.toString()) .header("Content-Length", Long.toString(body.contentLength())).build()); } }); Request request = new Request.Builder().url(server.url("/")).get().build(); client.newCall(request).execute(); RecordedRequest recordedRequest = server.takeRequest(); assertEquals("POST", recordedRequest.getMethod()); assertEquals("abc", recordedRequest.getBody().readUtf8()); }
From source file:com.facebook.stetho.okhttp.StethoInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { String requestId = mEventReporter.nextRequestId(); Request request = chain.request(); RequestBodyHelper requestBodyHelper = null; if (mEventReporter.isEnabled()) { requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId); OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request, requestBodyHelper);/*from w w w .j av a 2s . co m*/ mEventReporter.requestWillBeSent(inspectorRequest); } Response response; try { response = chain.proceed(request); } catch (IOException e) { if (mEventReporter.isEnabled()) { mEventReporter.httpExchangeFailed(requestId, e.toString()); } throw e; } if (mEventReporter.isEnabled()) { if (requestBodyHelper != null && requestBodyHelper.hasBody()) { requestBodyHelper.reportDataSent(); } Connection connection = chain.connection(); mEventReporter .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection)); ResponseBody body = response.body(); MediaType contentType = null; InputStream responseStream = null; if (body != null) { contentType = body.contentType(); responseStream = body.byteStream(); } responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId)); if (responseStream != null) { response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build(); } } return response; }
From source file:com.granita.contacticloudsync.syncadapter.ContactsSyncManager.java
License:Open Source License
@Override protected void queryCapabilities() throws DavException, IOException, HttpException { // prepare remote address book hasVCard4 = false;// w ww .ja v a 2 s . co m davCollection.propfind(0, SupportedAddressData.NAME, GetCTag.NAME); SupportedAddressData supportedAddressData = (SupportedAddressData) davCollection.properties .get(SupportedAddressData.NAME); if (supportedAddressData != null) for (MediaType type : supportedAddressData.types) if ("text/vcard; version=4.0".equalsIgnoreCase(type.toString())) hasVCard4 = true; log.info("Server advertises VCard/4 support: " + hasVCard4); }
From source file:com.hileone.restretrofit.request.RequestBuilder.java
License:Apache License
Request build() { HttpUrl url;/* w ww. ja v a2s .com*/ 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. url = baseUrl.resolve(relativeUrl); } RequestBody body = this.body; if (body == null) { // Try to pull from one of the builders. if (formEncodingBuilder != null) { body = formEncodingBuilder.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(); }
From source file:com.mobimvp.cliques.util.StethoInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { String requestId = String.valueOf(mNextRequestId.getAndIncrement()); Request request = chain.request(); int requestSize = 0; if (mEventReporter.isEnabled()) { OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request); mEventReporter.requestWillBeSent(inspectorRequest); byte[] requestBody = inspectorRequest.body(); if (requestBody != null) { requestSize += requestBody.length; }/*from ww w . j a v a 2 s . c o m*/ } Response response; try { response = chain.proceed(request); } catch (IOException e) { if (mEventReporter.isEnabled()) { mEventReporter.httpExchangeFailed(requestId, e.toString()); } throw e; } if (mEventReporter.isEnabled()) { if (requestSize > 0) { mEventReporter.dataSent(requestId, requestSize, requestSize); } Connection connection = chain.connection(); mEventReporter .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection)); ResponseBody body = response.body(); MediaType contentType = null; InputStream responseStream = null; if (body != null) { contentType = body.contentType(); responseStream = body.byteStream(); } responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId)); if (responseStream != null) { response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build(); } } return response; }
From source file:com.taobao.weex.devtools.inspector.network.OkHttpInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { String requestId = String.valueOf(mNextRequestId.getAndIncrement()); Request request = chain.request(); RequestBodyHelper requestBodyHelper = null; if (mEventReporter.isEnabled()) { requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId); OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request, requestBodyHelper);/*from w w w . j a v a 2 s . c o m*/ mEventReporter.requestWillBeSent(inspectorRequest); } Response response; try { response = chain.proceed(request); } catch (IOException e) { if (mEventReporter.isEnabled()) { mEventReporter.httpExchangeFailed(requestId, e.toString()); } throw e; } if (mEventReporter.isEnabled()) { if (requestBodyHelper != null && requestBodyHelper.hasBody()) { requestBodyHelper.reportDataSent(); } Connection connection = chain.connection(); mEventReporter .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection)); ResponseBody body = response.body(); MediaType contentType = null; InputStream responseStream = null; if (body != null) { contentType = body.contentType(); responseStream = body.byteStream(); } responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId)); if (responseStream != null) { response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build(); } } return response; }
From source file:com.yandex.disk.rest.RestClientIO.java
License:Apache License
void downloadUrl(final String url, final DownloadListener downloadListener) throws IOException, CancelledDownloadException, DownloadNoSpaceAvailableException, HttpCodeException { Request.Builder req = buildRequest().url(url); long length = downloadListener.getLocalLength(); String ifTag = "If-None-Match"; if (length >= 0) { ifTag = "If-Range"; StringBuilder contentRange = new StringBuilder(); contentRange.append("bytes=").append(length).append("-"); logger.debug("Range: " + contentRange); req.addHeader("Range", contentRange.toString()); }/*from w w w . j av a2 s .c om*/ String etag = downloadListener.getETag(); if (etag != null) { logger.debug(ifTag + ": " + etag); req.addHeader(ifTag, etag); } Request request = req.build(); Response response = client.newCall(request).execute(); boolean partialContent = false; int code = response.code(); switch (code) { case 200: // OK break; case 206: partialContent = true; break; case 304: throw new FileNotModifiedException(code); case 404: throw new NotFoundException(code); case 416: throw new RangeNotSatisfiableException(code); default: throw new HttpCodeException(code); } ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); logger.debug("download: contentLength=" + contentLength); long loaded; if (partialContent) { ContentRangeResponse contentRangeResponse = parseContentRangeHeader(response.header("Content-Range")); logger.debug("download: contentRangeResponse=" + contentRangeResponse); if (contentRangeResponse != null) { loaded = contentRangeResponse.getStart(); contentLength = contentRangeResponse.getSize(); } else { loaded = length; } } else { loaded = 0; if (contentLength < 0) { contentLength = 0; } } OutputStream os = null; try { downloadListener.setStartPosition(loaded); MediaType contentTypeHeader = responseBody.contentType(); if (contentTypeHeader != null) { downloadListener.setContentType(contentTypeHeader.toString()); } downloadListener.setContentLength(contentLength); int count; InputStream content = responseBody.byteStream(); os = downloadListener.getOutputStream(partialContent); final byte[] downloadBuffer = new byte[1024]; while ((count = content.read(downloadBuffer)) != -1) { if (downloadListener.hasCancelled()) { logger.info("Downloading " + url + " canceled"); client.cancel(request.tag()); throw new CancelledDownloadException(); } os.write(downloadBuffer, 0, count); loaded += count; downloadListener.updateProgress(loaded, contentLength); } } catch (CancelledDownloadException ex) { throw ex; } catch (Exception e) { logger.warn(e.getMessage(), e); client.cancel(request.tag()); if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof DownloadNoSpaceAvailableException) { throw (DownloadNoSpaceAvailableException) e; } else { // never happen throw new RuntimeException(e); } } finally { try { if (os != null) { os.close(); } } catch (IOException ex) { // nothing } try { response.body().close(); } catch (IOException | NullPointerException ex) { logger.warn(ex.getMessage(), ex); } } }
From source file:net.ltgt.resteasy.client.okhttp.OkHttpClientEngine.java
License:Apache License
private RequestBody createRequestBody(final ClientInvocation request) { if (request.getEntity() == null) { return null; }/* w w w . ja va2s . c o m*/ // NOTE: this will invoke WriterInterceptors which can possibly change the request, // so it must be done first, before reading any header. final Buffer buffer = new Buffer(); try { request.writeRequestBody(buffer.outputStream()); } catch (IOException e) { throw new RuntimeException(e); } javax.ws.rs.core.MediaType mediaType = request.getHeaders().getMediaType(); final MediaType contentType = (mediaType == null) ? null : MediaType.parse(mediaType.toString()); return new RequestBody() { @Override public long contentLength() throws IOException { return buffer.size(); } @Override public MediaType contentType() { return contentType; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer, buffer.size()); } }; }
From source file:org.hawkular.agent.monitor.dynamicprotocol.prometheus.HawkularPrometheusScraper.java
License:Apache License
@Override protected OpenConnectionDetails openConnection(URL endpointUrl) throws IOException { Configuration.Builder bldr = new Configuration.Builder().useSsl(endpointUrl.getProtocol().equals("https")) .sslContext(sslContext).username(endpointConfig.getConnectionData().getUsername()) .password(endpointConfig.getConnectionData().getPassword()); BaseHttpClientGenerator httpClientGen = new BaseHttpClientGenerator(bldr.build()); OkHttpClient httpClient = httpClientGen.getHttpClient(); Request request = buildGetRequest(endpointUrl, httpClientGen); Call call = httpClient.newCall(request); Response response = call.execute(); ResponseBody responseBody = response.body(); InputStream inputStream = responseBody.byteStream(); MediaType contentType = responseBody.contentType(); return new OpenConnectionDetails(inputStream, (contentType != null) ? contentType.toString() : null); }