List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
From source file:com.drjing.xibao.common.http.AsyncHttpResponseHandler.java
License:Apache License
protected void sendSuccessMessage(Response response) { try {/* w w w . j av a2 s. c o m*/ sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[] { new Integer(response.code()), response.headers(), response.body().string() })); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.enstage.wibmo.util.HttpUtil.java
License:Apache License
public static String postDataUseOkHttp(String posturl, byte postData[], boolean useCache, MediaType mediaType) throws Exception { URL url;/* w ww .j a v a2 s . com*/ long stime = System.currentTimeMillis(); try { url = new URL(posturl); RequestBody body = RequestBody.create(mediaType, postData); Request.Builder builder = new Request.Builder(); builder.url(url); if (useCache == false) { builder.addHeader("Cache-Control", "no-cache"); } builder.post(body); Request request = builder.build(); if (okhttpinit == false) { Log.w(TAG, "WibmoSDK init was false; " + client.getSslSocketFactory()); if (client.getSslSocketFactory() == null) { setSSLstuff(); } } Response res = client.newCall(request).execute(); // Read the response. if (res.code() != HttpURLConnection.HTTP_OK) { Log.e(TAG, "Bad res code: " + res.code()); Log.e(TAG, "Url was: " + posturl.toString()); Log.e(TAG, "HTTP response: " + res.message() + "; " + res.body().string()); return null; } return res.body().string(); } finally { long etime = System.currentTimeMillis(); Log.i(TAG, "time dif: " + (etime - stime)); } }
From source file:com.example.ivy.picassodemo.MyOkHttpDownloader.java
License:Apache License
@Override public Response load(Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl = null;// w ww. j a v a 2 s . co m if (networkPolicy != 0) { if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } } Request.Builder builder = new Request.Builder().url(uri.toString()); if (cacheControl != null) { builder.cacheControl(cacheControl); } com.squareup.okhttp.Response response = client.newCall(builder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }
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 v a 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();/* w ww .j av a 2 s. com*/ 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.artifact_cache.HttpArtifactCache.java
License:Apache License
protected void storeImpl(ImmutableSet<RuleKey> ruleKeys, final ImmutableMap<String, String> metadata, final Path file, final Finished.Builder eventBuilder) throws IOException { // Build the request, hitting the multi-key endpoint. Request.Builder builder = new Request.Builder(); builder.url(uri.resolve("/artifacts/key").toURL()); final HttpArtifactCacheBinaryProtocol.StoreRequest storeRequest = new HttpArtifactCacheBinaryProtocol.StoreRequest( ruleKeys, metadata, new ByteSource() { @Override/*from w ww . j av a 2s . c om*/ public InputStream openStream() throws IOException { return projectFilesystem.newFileInputStream(file); } }); eventBuilder.setRequestSizeBytes(storeRequest.getContentLength()); // Wrap the file into a `RequestBody` which uses `ProjectFilesystem`. builder.put(new RequestBody() { @Override public MediaType contentType() { return OCTET_STREAM; } @Override public long contentLength() throws IOException { return storeRequest.getContentLength(); } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { StoreWriteResult writeResult = storeRequest.write(bufferedSink.outputStream()); eventBuilder.setArtifactSizeBytes(writeResult.getArtifactSizeBytes()); eventBuilder.setArtifactContentHash(writeResult.getArtifactContentHashCode().toString()); } }); // Dispatch the store operation and verify it succeeded. Request request = builder.build(); Response response = storeCall(request); final boolean requestFailed = response.code() != HttpURLConnection.HTTP_ACCEPTED; if (requestFailed) { reportFailure("store(%s, %s): unexpected response: %d", uri, ruleKeys, response.code()); } eventBuilder.setWasUploadSuccessful(!requestFailed); }
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 . j a v a 2s .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.rules.HttpArtifactCache.java
License:Apache License
public void storeImpl(RuleKey ruleKey, final File file) throws IOException { Request request = createRequestBuilder(ruleKey.toString()).put(new RequestBody() { @Override/*from w w w.jav a 2 s .c om*/ public MediaType contentType() { return OCTET_STREAM; } @Override public long contentLength() throws IOException { return Long.SIZE / Byte.SIZE + projectFilesystem.getFileSize(file.toPath()) + hashFunction.bits() / Byte.SIZE; } @Override public void writeTo(BufferedSink sink) throws IOException { try (DataOutputStream output = new DataOutputStream(sink.outputStream()); InputStream input = projectFilesystem.newFileInputStream(file.toPath()); HashingInputStream hasher = new HashingInputStream(hashFunction, input)) { output.writeLong(projectFilesystem.getFileSize(file.toPath())); ByteStreams.copy(hasher, output); output.write(hasher.hash().asBytes()); } } }).build(); Response response = storeCall(request); if (response.code() != HttpURLConnection.HTTP_ACCEPTED) { LOGGER.warn("store(%s): unexpected response: %d", ruleKey, response.code()); } }
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// w w w. ja 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(); } } } }); }
From source file:com.facebook.react.devsupport.DevServerHelper.java
License:Open Source License
public void isPackagerRunning(final PackagerStatusCallback callback) { String statusURL = createPacakgerStatusURL(getDebugServerHost()); Request request = new Request.Builder().url(statusURL).build(); mClient.newCall(request).enqueue(new Callback() { @Override/* w ww . j a va 2 s . c o m*/ public void onFailure(Request request, IOException e) { Log.e(ReactConstants.TAG, "IOException requesting status from packager", e); callback.onPackagerStatusFetched(false); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { Log.e(ReactConstants.TAG, "Got non-success http code from packager when requesting status: " + response.code()); callback.onPackagerStatusFetched(false); return; } ResponseBody body = response.body(); if (body == null) { Log.e(ReactConstants.TAG, "Got null body response from packager when requesting status"); callback.onPackagerStatusFetched(false); return; } if (!PACKAGER_OK_STATUS.equals(body.string())) { Log.e(ReactConstants.TAG, "Got unexpected response from packager when requesting status: " + body.string()); callback.onPackagerStatusFetched(false); return; } callback.onPackagerStatusFetched(true); } }); }