List of usage examples for com.squareup.okhttp Call execute
public Response execute() throws IOException
From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java
License:Apache License
private <L> void performResourceTypeSync( Offline<org.hawkular.inventory.api.model.ResourceType.Blueprint> resourceTypeStructure, String tenantIdToUse) {// w w w . j a va2s . c o m if (resourceTypeStructure.getRoot() != null) { try { SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build(); SyncRequest<org.hawkular.inventory.api.model.ResourceType.Blueprint> sync; sync = new SyncRequest<>(syncConfig, resourceTypeStructure); StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(), AsyncInventoryStorage.this.config.getInventoryContext()); url.append("sync"); url.append("/f;").append(this.feedId); url.append("/rt;").append(Util.urlEncode(resourceTypeStructure.getRoot().getId())); String jsonPayload = Util.toJson(sync); Map<String, String> headers = getTenantHeader(tenantIdToUse); log.tracef("Syncing resource type to inventory: headers=[%s] body=[%s]", headers, jsonPayload); Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload); Call call = this.httpClientBuilder.getHttpClient().newCall(request); final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time(); Response response = call.execute(); try { final long durationNanos = timer.stop(); log.tracef("Received sync response from inventory: code [%d]", response.code()); // HTTP status of 204 means success, anything else is an error if (response.code() != 204) { throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); } diagnostics.getInventoryRate().mark(1); if (log.isDebugEnabled()) { log.debugf("Took [%d]ms to sync resource type to inventory", TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS)); } } finally { response.body().close(); } } catch (InterruptedException ie) { log.errorFailedToStoreInventoryData(ie); Thread.currentThread().interrupt(); // preserve interrupt } catch (Exception e) { log.errorFailedToStoreInventoryData(e); diagnostics.getStorageErrorRate().mark(1); } } return; }
From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java
License:Apache License
private <L> void performMetricTypeSync( Offline<org.hawkular.inventory.api.model.MetricType.Blueprint> metricTypeStructure, String tenantIdToUse) {/*from ww w . ja v a2s .co m*/ if (metricTypeStructure.getRoot() != null) { try { SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build(); SyncRequest<org.hawkular.inventory.api.model.MetricType.Blueprint> sync; sync = new SyncRequest<>(syncConfig, metricTypeStructure); StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(), AsyncInventoryStorage.this.config.getInventoryContext()); url.append("sync"); url.append("/f;").append(this.feedId); url.append("/mt;").append(Util.urlEncode(metricTypeStructure.getRoot().getId())); String jsonPayload = Util.toJson(sync); Map<String, String> headers = getTenantHeader(tenantIdToUse); log.tracef("Syncing metric type to inventory: headers=[%s] body=[%s]", headers, jsonPayload); Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload); Call call = this.httpClientBuilder.getHttpClient().newCall(request); final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time(); Response response = call.execute(); try { final long durationNanos = timer.stop(); log.tracef("Received sync response from inventory: code [%d]", response.code()); // HTTP status of 204 means success, anything else is an error if (response.code() != 204) { throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message() + "], url=[" + request.urlString() + "]"); } diagnostics.getInventoryRate().mark(1); if (log.isDebugEnabled()) { log.debugf("Took [%d]ms to sync metric type to inventory", TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS)); } } finally { response.body().close(); } } catch (InterruptedException ie) { log.errorFailedToStoreInventoryData(ie); Thread.currentThread().interrupt(); // preserve interrupt } catch (Exception e) { log.errorFailedToStoreInventoryData(e); diagnostics.getStorageErrorRate().mark(1); } } return; }
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); }
From source file:org.mariotaku.twidere.util.net.OkHttpRestClient.java
License:Open Source License
@NonNull @Override//from w w w .j av a 2s . c om public RestHttpResponse execute(RestHttpRequest restHttpRequest) throws IOException { final Request.Builder builder = new Request.Builder(); builder.method(restHttpRequest.getMethod(), RestToOkBody.wrap(restHttpRequest.getBody())); builder.url(restHttpRequest.getUrl()); final List<Pair<String, String>> headers = restHttpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers) { builder.addHeader(header.first, header.second); } } final Call call = client.newCall(builder.build()); return new OkRestHttpResponse(call.execute()); }
From source file:org.quantumbadger.redreader.http.okhttp.OKHTTPBackend.java
License:Open Source License
@Override public Request prepareRequest(final Context context, final RequestDetails details) { final com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder(); builder.header("User-Agent", Constants.ua(context)); final List<PostField> postFields = details.getPostFields(); if (postFields != null) { builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), PostField.encodeList(postFields))); } else {/*from w ww.j a va2s .co m*/ builder.get(); } builder.url(details.getUrl().toString()); builder.cacheControl(CacheControl.FORCE_NETWORK); final AtomicReference<Call> callRef = new AtomicReference<>(); return new Request() { public void executeInThisThread(final Listener listener) { final Call call = mClient.newCall(builder.build()); callRef.set(call); try { final Response response; try { response = call.execute(); } catch (IOException e) { listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, e, null); return; } final int status = response.code(); if (status == 200 || status == 202) { final ResponseBody body = response.body(); final InputStream bodyStream; final Long bodyBytes; if (body != null) { bodyStream = body.byteStream(); bodyBytes = body.contentLength(); } else { // TODO error bodyStream = null; bodyBytes = null; } final String contentType = response.header("Content-Type"); listener.onSuccess(contentType, bodyBytes, bodyStream); } else { listener.onError(CacheRequest.REQUEST_FAILURE_REQUEST, null, status); } } catch (Throwable t) { listener.onError(CacheRequest.REQUEST_FAILURE_CONNECTION, t, null); } } @Override public void cancel() { final Call call = callRef.getAndSet(null); if (call != null) { call.cancel(); } } @Override public void addHeader(final String name, final String value) { builder.addHeader(name, value); } }; }
From source file:org.sonarqube.ws.client.HttpConnector.java
License:Open Source License
private HttpResponse doCall(Request okRequest) { Call call = okHttpClient.newCall(okRequest); try {// w w w . j ava 2s . c om Response okResponse = call.execute(); return new HttpResponse(okResponse); } catch (IOException e) { throw new IllegalStateException("Fail to request " + okRequest.urlString(), e); } }
From source file:pct.droid.base.youtube.YouTubeData.java
License:Open Source License
/** * Calculate the YouTube URL to load the video. Includes retrieving a token that YouTube * requires to play the video./*w ww. ja va 2 s .co m*/ * * @param quality quality of the video. 17=low, 18=high * @param fallback whether to fallback to lower quality in case the supplied quality is not available * @param videoId the id of the video * @return the url string that will retrieve the video * @throws java.io.IOException */ public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException { String uriStr = null; OkHttpClient client = PopcornApplication.getHttpClient(); Request.Builder request = new Request.Builder(); request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId); Call call = client.newCall(request.build()); Response response = call.execute(); String infoStr = response.body().string(); String[] args = infoStr.split("&"); Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { String[] valStrArr = arg.split("="); if (valStrArr.length >= 2) { argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1])); } } //Find out the URI string from the parameters //Populate the list of formats for the video String fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8"); ArrayList<Format> formats = new ArrayList<Format>(); if (null != fmtList) { String formatStrs[] = fmtList.split(","); for (String lFormatStr : formatStrs) { Format format = new Format(lFormatStr); formats.add(format); } } //Populate the list of streams for the video String streamList = argMap.get("url_encoded_fmt_stream_map"); if (null != streamList) { String streamStrs[] = streamList.split(","); ArrayList<VideoStream> streams = new ArrayList<VideoStream>(); for (String streamStr : streamStrs) { VideoStream lStream = new VideoStream(streamStr); streams.add(lStream); } //Search for the given format in the list of video formats // if it is there, select the corresponding stream // otherwise if fallback is requested, check for next lower format int formatId = Integer.parseInt(quality); Format searchFormat = new Format(formatId); while (!formats.contains(searchFormat) && fallback) { int oldId = searchFormat.getId(); int newId = getSupportedFallbackId(oldId); if (oldId == newId) { break; } searchFormat = new Format(newId); } int index = formats.indexOf(searchFormat); if (index >= 0) { VideoStream searchStream = streams.get(index); uriStr = searchStream.getUrl(); } } //Return the URI string. It may be null if the format (or a fallback format if enabled) // is not found in the list of formats for the video return uriStr; }
From source file:retrofit.KOkHttpCall.java
License:Apache License
public Response<T> execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already executed"); executed = true;/*from ww w. ja va 2 s. c om*/ } com.squareup.okhttp.Request request = createRequest(); // ----------------------------------------------------------------------cgp String headerValue = request.header("RequestMode"); if (!TextUtils.isEmpty(headerValue)) { switch (headerValue) { case RequestMode.LOAD_NETWORK_ELSE_CACHE:// ?? com.squareup.okhttp.Call rawCall = client.newCall(request); if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; Response<T> response; try { response = parseResponse(rawCall.execute(), request); } catch (Exception e) { response = execCacheRequest(request); } return response; case RequestMode.LOAD_CACHE_ELSE_NETWORK:// ? // ---------------------? response = execCacheRequest(request); if (response != null) { return response; } // ---------------------? // case RequestMode.LOAD_DEFAULT: case RequestMode.LOAD_NETWORK_ONLY: default: break;// } } // ----------------------------------------------------------------------cgp com.squareup.okhttp.Call rawCall = client.newCall(request); if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; return parseResponse(rawCall.execute(), request); }
From source file:retrofit2.OkHttpCall.java
License:Apache License
@Override public Response<T> execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true;/*from ww w . java2s.c o m*/ } com.squareup.okhttp.Call rawCall = createRawCall(); if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; return parseResponse(rawCall.execute()); }