List of usage examples for com.squareup.okhttp Response body
ResponseBody body
To view the source code for com.squareup.okhttp Response body.
Click Source Link
From source file:com.example.jordan.sunshine.app.FetchWeatherTask.java
License:Apache License
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/*w ww .j av a 2 s. co m*/ String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. // HttpURLConnection urlConnection = null; // BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast // Ex URL: http://api.openweathermap.org/data/2.5/forecast/daily?q=92691&mode=json&units=metric&cnt=7 final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build(); try { URL url = new URL(builtUri.toString()); OkHttpClient client = new OkHttpClient(); //DEV Only - interceptor for Stetho. // TODO remove from release version automatically client.networkInterceptors().add(new StethoInterceptor()); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (response != null) { forecastJsonStr = response.body().string(); } } catch (IOException e) { Log.e(LOG_TAG, "Error: ", e); e.printStackTrace(); } if (forecastJsonStr != null) { try { getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } } return null; }
From source file:com.example.sample2.ExampleFragment1.java
License:Apache License
@Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { final String body = response.body().string(); mSchedule = gson.fromJson(body, BBCSchedule.class); scheduleList.post(new Runnable() { @Override/*from ww w . jav a 2 s. c om*/ public void run() { scheduleList.setAdapter(new ScheduleAdapter(mSchedule.getSchedule().getDay().getBroadcasts())); } }); } }
From source file:com.example.weatherforecast.service.HttpConnection.java
License:Open Source License
private String handleResponse(Response response) throws HttpException { try {//from ww w . j a va 2s .com switch (response.code()) { case 200: return response.body().string(); default: throw new HttpException(ErrorCode.HTTP_RESPONSE_CODE_UNKNOWN, "Server response: " + response); } } catch (IOException e) { throw new HttpException(ErrorCode.IO_EXCEPTION, e.getMessage()); } }
From source file:com.facebook.buck.artifact_cache.HttpArtifactCache.java
License:Apache License
public CacheResult fetchImpl(RuleKey ruleKey, Path file, final Finished.Builder eventBuilder) throws IOException { Request request = new Request.Builder().url(uri.resolve("/artifacts/key/" + ruleKey.toString()).toURL()) .get().build();/* ww w .java2 s .c om*/ Response response = fetchCall(request); eventBuilder.setResponseSizeBytes(response.body().contentLength()); try (DataInputStream input = new DataInputStream( new FullyReadOnCloseInputStream(response.body().byteStream()))) { if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) { LOGGER.info("fetch(%s, %s): cache miss", uri, ruleKey); return CacheResult.miss(); } if (response.code() != HttpURLConnection.HTTP_OK) { String msg = String.format("unexpected response: %d", response.code()); reportFailure("fetch(%s, %s): %s", uri, ruleKey, msg); eventBuilder.setErrorMessage(msg); return CacheResult.error(name, msg); } // Setup a temporary file, which sits next to the destination, to write to and // make sure all parent dirs exist. projectFilesystem.createParentDirs(file); Path temp = projectFilesystem.createTempFile(file.getParent(), file.getFileName().toString(), ".tmp"); FetchResponseReadResult fetchedData; try (OutputStream tempFileOutputStream = projectFilesystem.newFileOutputStream(temp)) { fetchedData = HttpArtifactCacheBinaryProtocol.readFetchResponse(input, tempFileOutputStream); } eventBuilder.setResponseSizeBytes(fetchedData.getResponseSizeBytes()); eventBuilder.setArtifactContentHash(fetchedData.getArtifactOnlyHashCode().toString()); // Verify that we were one of the rule keys that stored this artifact. if (!fetchedData.getRuleKeys().contains(ruleKey)) { String msg = "incorrect key name"; reportFailure("fetch(%s, %s): %s", uri, ruleKey, msg); eventBuilder.setErrorMessage(msg); return CacheResult.error(name, msg); } // Now form the checksum on the file we got and compare it to the checksum form the // the HTTP header. If it's incorrect, log this and return a miss. if (!fetchedData.getExpectedHashCode().equals(fetchedData.getActualHashCode())) { String msg = "artifact had invalid checksum"; reportFailure("fetch(%s, %s): %s", uri, ruleKey, msg); projectFilesystem.deleteFileAtPath(temp); eventBuilder.setErrorMessage(msg); return CacheResult.error(name, msg); } // Finally, move the temp file into it's final place. projectFilesystem.move(temp, file, StandardCopyOption.REPLACE_EXISTING); LOGGER.info("fetch(%s, %s): cache hit", uri, ruleKey); return CacheResult.hit(name, fetchedData.getMetadata()); } }
From source file:com.facebook.buck.rules.HttpArtifactCache.java
License:Apache License
public CacheResult fetchImpl(RuleKey ruleKey, File file) throws IOException { Request request = createRequestBuilder(ruleKey.toString()).get().build(); Response response = fetchCall(request); if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) { LOGGER.info("fetch(%s): cache miss", ruleKey); return CacheResult.MISS; }//from w w w. jav a 2 s. com if (response.code() != HttpURLConnection.HTTP_OK) { LOGGER.warn("fetch(%s): unexpected response: %d", ruleKey, response.code()); return CacheResult.MISS; } // The hash code shipped with the artifact to/from the cache. HashCode expectedHashCode, actualHashCode; // Setup a temporary file, which sits next to the destination, to write to and // make sure all parent dirs exist. Path path = file.toPath(); projectFilesystem.createParentDirs(path); Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp"); // Open the stream to server just long enough to read the hash code and artifact. try (DataInputStream input = new DataInputStream(response.body().byteStream())) { // First, extract the size of the file data portion, which we put in the beginning of // the artifact. long length = input.readLong(); // Now, write the remaining response data to the temp file, while grabbing the hash. try (BoundedInputStream boundedInput = new BoundedInputStream(input, length); HashingInputStream hashingInput = new HashingInputStream(hashFunction, boundedInput); OutputStream output = projectFilesystem.newFileOutputStream(temp)) { ByteStreams.copy(hashingInput, output); actualHashCode = hashingInput.hash(); } // Lastly, extract the hash code from the end of the request data. byte[] hashCodeBytes = new byte[hashFunction.bits() / Byte.SIZE]; ByteStreams.readFully(input, hashCodeBytes); expectedHashCode = HashCode.fromBytes(hashCodeBytes); // We should be at the end of output -- verify this. Also, we could just try to read a // single byte here, instead of all remaining input, but some network stack implementations // require that we exhaust the input stream before the connection can be reusable. try (OutputStream output = ByteStreams.nullOutputStream()) { if (ByteStreams.copy(input, output) != 0) { LOGGER.warn("fetch(%s): unexpected end of input", ruleKey); return CacheResult.MISS; } } } // Now form the checksum on the file we got and compare it to the checksum form the // the HTTP header. If it's incorrect, log this and return a miss. if (!expectedHashCode.equals(actualHashCode)) { LOGGER.warn("fetch(%s): artifact had invalid checksum", ruleKey); projectFilesystem.deleteFileAtPath(temp); return CacheResult.MISS; } // Finally, move the temp file into it's final place. projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING); LOGGER.info("fetch(%s): cache hit", ruleKey); return CacheResult.HTTP_HIT; }
From source file:com.facebook.buck.slb.LoadBalancedService.java
License:Apache License
@Override public Response makeRequest(String path, Request.Builder requestBuilder) throws IOException { URI server = slb.getBestServer(); LoadBalancedServiceEventData.Builder data = LoadBalancedServiceEventData.builder().setServer(server); requestBuilder.url(SingleUriService.getFullUrl(server, path)); Request request = requestBuilder.build(); if (request.body() != null && request.body().contentLength() != -1) { data.setRequestSizeBytes(request.body().contentLength()); }//from w ww . ja v a2 s .com Call call = client.newCall(request); try { Response response = call.execute(); if (response.body() != null && response.body().contentLength() != -1) { data.setResponseSizeBytes(response.body().contentLength()); } slb.reportRequestSuccess(server); return response; } catch (IOException e) { data.setException(e); slb.reportRequestException(server); throw new IOException(e); } finally { eventBus.post(new LoadBalancedServiceEvent(data.build())); } }
From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetcher.java
License:Open Source License
@Override public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) { fetchState.submitTime = SystemClock.elapsedRealtime(); final Uri uri = fetchState.getUri(); final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()).get().build(); final Call call = mOkHttpClient.newCall(request); fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() { @Override/* w w w.ja va2 s.co m*/ public void onCancellationRequested() { if (Looper.myLooper() != Looper.getMainLooper()) { call.cancel(); } else { mCancellationExecutor.execute(new Runnable() { @Override public void run() { call.cancel(); } }); } } }); call.enqueue(new com.squareup.okhttp.Callback() { @Override public void onResponse(Response response) { fetchState.responseTime = SystemClock.elapsedRealtime(); final ResponseBody body = response.body(); try { long contentLength = body.contentLength(); if (contentLength < 0) { contentLength = 0; } callback.onResponse(body.byteStream(), (int) contentLength); } catch (Exception e) { handleException(call, e, callback); } finally { try { body.close(); } catch (Exception e) { FLog.w(TAG, "Exception when closing response body", e); } } } @Override public void onFailure(final Request request, final IOException e) { handleException(call, e, callback); } }); }
From source file:com.facebook.imagepipeline.backends.okhttp.OkHttpNetworkFetchProducer.java
License:Open Source License
@Override protected void fetchImage(final NfpRequestState requestState) { final Uri uri = requestState.getUri(); final Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()).get().build(); final Call call = mOkHttpClient.newCall(request); if (mCancellable) { requestState.getContext().addCallbacks(new BaseProducerContextCallbacks() { @Override/* www .jav a 2s.c om*/ public void onCancellationRequested() { call.cancel(); } }); } call.enqueue(new Callback() { @Override public void onResponse(Response response) { final ResponseBody body = response.body(); try { long contentLength = body.contentLength(); if (contentLength < 0) { contentLength = 0; } processResult(requestState, body.byteStream(), (int) contentLength, false); } catch (IOException ioe) { handleException(call, requestState, ioe); } finally { try { body.close(); } catch (IOException ioe) { FLog.w(TAG, "Exception when closing response body", ioe); } } } @Override public void onFailure(final Request request, final IOException e) { handleException(call, requestState, e); } }); }
From source file:com.facebook.react.bridge.webworkers.WebWorkers.java
License:Open Source License
/** * Utility method used to help develop web workers on debug builds. In release builds, worker * scripts need to be packaged with the app, but in dev mode we want to fetch/reload the worker * script on the fly from the packager. This method fetches the given URL *synchronously* and * writes it to the specified temp file. * * This is exposed from Java only because we don't want to add a C++ networking library dependency * * NB: The caller is responsible for deleting the file specified by outFileName when they're done * with it./* w w w . j a v a 2s .com*/ * NB: We write to a temp file instead of returning a String because, depending on the size of the * worker script, allocating the full script string on the Java heap can cause an OOM. */ public static void downloadScriptToFileSync(String url, String outFileName) { if (!ReactBuildConfig.DEBUG) { throw new RuntimeException( "For security reasons, downloading scripts is only allowed in debug builds."); } OkHttpClient client = new OkHttpClient(); final File out = new File(outFileName); Request request = new Request.Builder().url(url).build(); try { Response response = client.newCall(request).execute(); Sink output = Okio.sink(out); Okio.buffer(response.body().source()).readAll(output); } catch (IOException e) { throw new RuntimeException("Exception downloading web worker script to file", e); } }
From source file:com.facebook.react.devsupport.DevServerHelper.java
License:Open Source License
public void downloadBundleFromURL(final BundleDownloadCallback callback, final String jsModulePath, final File outputFile) { final String bundleURL = createBundleURL(getDebugServerHost(), jsModulePath, getDevMode()); Request request = new Request.Builder().url(bundleURL).build(); Call call = mClient.newCall(request); call.enqueue(new Callback() { @Override/*from w ww .j a v a 2s . co m*/ public void onFailure(Request request, IOException e) { callback.onFailure(e); } @Override public void onResponse(Response response) throws IOException { // Check for server errors. If the server error has the expected form, fail with more info. if (!response.isSuccessful()) { String body = response.body().string(); DebugServerException debugServerException = DebugServerException.parse(body); if (debugServerException != null) { callback.onFailure(debugServerException); } else { callback.onFailure(new IOException("Unexpected response code: " + response.code())); } return; } Sink output = null; try { output = Okio.sink(outputFile); Okio.buffer(response.body().source()).readAll(output); callback.onSuccess(); } finally { if (output != null) { output.close(); } } } }); }