List of usage examples for com.squareup.okhttp Call execute
public Response execute() throws IOException
From source file:com.mozillaonline.providers.downloads.DownloadThread.java
License:Apache License
/** * Fully execute a single download request - setup and send the request, * handle the response, and transfer the data to the destination file. *//* ww w .ja v a 2 s. c o m*/ private void executeDownload(InnerState innerState, State state, Call call) throws StopRequest, RetryDownload, IOException { byte data[] = new byte[Constants.BUFFER_SIZE]; // check just before sending the request to avoid using an invalid // connection at all checkConnectivity(state); Response response = call.execute(); handleExceptionalStatus(state, innerState, response); if (Constants.LOGV) { Log.v(Constants.TAG, "received response for " + mInfo.mUri); } processResponseHeaders(state, innerState, response); InputStream entityStream = openResponseEntity(state, response); transferData(state, innerState, data, entityStream); }
From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java
License:Apache License
public Response<T> execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already executed"); executed = true;/*from www. ja v a2 s .c o m*/ } com.squareup.okhttp.Call rawCall = createRawCall(); if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; return parseResponse(rawCall.execute()); }
From source file:com.parse.ParseOkHttpClient.java
License:Open Source License
@Override /* package */ ParseHttpResponse executeInternal(ParseHttpRequest parseRequest) throws IOException { Request okHttpRequest = getRequest(parseRequest); Call okHttpCall = okHttpClient.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); return getResponse(okHttpResponse); }
From source file:com.peach.masktime.module.net.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); LogUtils.i(TAG, "timeoutMs = " + timeoutMs); client.setProxy(Proxy.NO_PROXY); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//from w ww . j a v a 2s.c om for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.phattn.vnexpressnews.io.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/* w ww . ja v a2 s . c om*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, length = responseHeaders.size(); i < length; i++) { final String name = responseHeaders.name(i); final String value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.shahul3d.indiasatelliteweather.service.DownloaderService.java
License:Open Source License
@Background public void downloadMap(int mapID) { //TODO: Check internet String mapType = appConstants.getMapType(mapID); String lastModifiedHeader = ""; Log.d("Download requested for map type: " + mapType); updateDownloadStatus(mapID, 0);/*ww w.j ava 2s .c om*/ final String URL = appConstants.MAP_URL.get(mapType); try { Call call = httpClient.newCall(new Request.Builder().url(URL).get().build()); Response response = call.execute(); //TODO: These caching headers should be stored on preferences. String eTagHeader = response.header("ETag", ""); lastModifiedHeader = response.header("Last-Modified", ""); // Log.d("eTagHeader: " + eTagHeader); Log.d("last modified: " + lastModifiedHeader); // Log.d("\nN/W counts: " + httpClient.getCache().getNetworkCount() + "\nReq Counts: " + httpClient.getCache().getRequestCount() + "\nCache Hits: " + httpClient.getCache().getHitCount()); if (response.code() == 200) { InputStream inputStream = null; ByteArrayOutputStream outArrrayIPStream = null; try { inputStream = response.body().byteStream(); outArrrayIPStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int statusUpdateTrigger = 0; long downloaded = 0; long responseSize = response.body().contentLength(); Log.d("Total size: " + responseSize); for (int count; (count = inputStream.read(buffer)) != -1;) { outArrrayIPStream.write(buffer, 0, count); downloaded += count; statusUpdateTrigger++; // Log.d(String.format("%d / %d", downloaded, responseSize)); //Update download status if (statusUpdateTrigger > appConstants.STATUS_UPDATE_THRESHOLD) { // Thread.sleep(3000); statusUpdateTrigger = 0; Long downloadedPercent = downloaded * appConstants.MAX_DOWNLOAD_PROGRESS / responseSize; Log.d("downloaded percent: " + downloadedPercent); updateDownloadStatus(mapID, downloadedPercent.intValue()); } } byte[] responseImage = outArrrayIPStream.toByteArray(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; Bitmap bmp = BitmapFactory.decodeByteArray(responseImage, 0, responseImage.length, options); bmp = removeMapBorders(mapType, bmp); //Save downloaded image for offline use. saveDownloadedMap(mapType, bmp); updateDownloadStatus(mapID, 100); } catch (IOException ignore) { trackException("MAP download & parser error", ignore); broadcastDownloadStatus(mapID, false); //Error on fetching & organizing the binary data. return; } finally { if (inputStream != null) { inputStream.close(); } if (outArrrayIPStream != null) { outArrrayIPStream.close(); } } } else { trackException("res code other than 200: " + response.code(), null); Log.d("res code other than 200 " + response.code()); return; } } catch (IOException e) { trackException("MAP download connection error", e); broadcastDownloadStatus(mapID, false); return; } preferenceUtil.updateLastModifiedTime(preference_General, mapType, lastModifiedHeader); broadcastDownloadStatus(mapID, true); }
From source file:com.xing.api.CallSpec.java
License:Apache License
/** * Synchronously executes the request and returns it's response. * * @throws IOException If a problem occurred while talking to the server. * @throws RuntimeException If an unexpected error occurred during execution or while parsing response. *///from www. j a v a2s .co m public Response<RT, ET> execute() throws IOException { synchronized (this) { if (executed) throw stateError("Call already executed"); executed = true; } Call rawCall = createRawCall(); if (canceled) rawCall.cancel(); this.rawCall = rawCall; return parseResponse(rawCall.execute()); }
From source file:com.ydh.gva.util.net.volley.toolbox.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); okHttpRequestBuilder.addHeader("clientos", "101"); okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + ""); okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + ""); okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + ""); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/*from w ww . j a v a2 s. c o m*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:de.schildbach.wallet.data.DynamicFeeLoader.java
License:Open Source License
private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile, final String userAgent) { final Stopwatch watch = Stopwatch.createStarted(); final Request.Builder request = new Request.Builder(); request.url(url);// ww w . j ava 2 s. c o m request.header("User-Agent", userAgent); if (targetFile.exists()) request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified()))); final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone(); httpClient.setConnectTimeout(5, TimeUnit.SECONDS); httpClient.setWriteTimeout(5, TimeUnit.SECONDS); httpClient.setReadTimeout(5, TimeUnit.SECONDS); final Call call = httpClient.newCall(request.build()); try { final Response response = call.execute(); final int status = response.code(); if (status == HttpURLConnection.HTTP_NOT_MODIFIED) { log.info("Dynamic fees not modified at {}, took {}", url, watch); } else if (status == HttpURLConnection.HTTP_OK) { final ResponseBody body = response.body(); final FileOutputStream os = new FileOutputStream(tempFile); Io.copy(body.byteStream(), os); os.close(); final Date lastModified = response.headers().getDate("Last-Modified"); if (lastModified != null) tempFile.setLastModified(lastModified.getTime()); body.close(); if (!tempFile.renameTo(targetFile)) throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile); watch.stop(); log.info("Dynamic fees fetched from {}, took {}", url, watch); } else { log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url); } } catch (final Exception x) { log.warn("Problem when fetching dynamic fees rates from " + url, x); } }
From source file:de.schildbach.wallet.data.ExchangeRatesProvider.java
License:Open Source License
private Map<String, ExchangeRate> requestExchangeRates() { final Stopwatch watch = Stopwatch.createStarted(); final Request.Builder request = new Request.Builder(); request.url(BITCOINAVERAGE_URL); request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try {//from w w w .j a va 2 s .co m final Response response = call.execute(); if (response.isSuccessful()) { final String content = response.body().string(); final JSONObject head = new JSONObject(content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (currencyCode.startsWith("BTC")) { final String fiatCurrencyCode = currencyCode.substring(3); if (!fiatCurrencyCode.equals(MonetaryFormat.CODE_BTC) && !fiatCurrencyCode.equals(MonetaryFormat.CODE_MBTC) && !fiatCurrencyCode.equals(MonetaryFormat.CODE_UBTC)) { final JSONObject exchangeRate = head.getJSONObject(currencyCode); final JSONObject averages = exchangeRate.getJSONObject("averages"); try { final Fiat rate = parseFiatInexact(fiatCurrencyCode, averages.getString("day")); if (rate.signum() > 0) rates.put(fiatCurrencyCode, new ExchangeRate( new org.bitcoinj.utils.ExchangeRate(rate), BITCOINAVERAGE_SOURCE)); } catch (final IllegalArgumentException x) { log.warn("problem fetching {} exchange rate from {}: {}", currencyCode, BITCOINAVERAGE_URL, x.getMessage()); } } } } watch.stop(); log.info("fetched exchange rates from {}, {} chars, took {}", BITCOINAVERAGE_URL, content.length(), watch); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", response.code(), BITCOINAVERAGE_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + BITCOINAVERAGE_URL, x); } return null; }