List of usage examples for com.squareup.okhttp Request.Builder cacheControl
CacheControl cacheControl
To view the source code for com.squareup.okhttp Request.Builder cacheControl.
Click Source Link
From source file:com.google.android.exoplayer.ext.okhttp.OkHttpDataSource.java
License:Apache License
/** * Establishes a connection.//from ww w.ja va 2 s .com */ private Request makeRequest(DataSpec dataSpec) { long position = dataSpec.position; long length = dataSpec.length; boolean allowGzip = (dataSpec.flags & DataSpec.FLAG_ALLOW_GZIP) != 0; HttpUrl url = HttpUrl.parse(dataSpec.uri.toString()); Request.Builder builder = new Request.Builder().url(url); if (cacheControl != null) { builder.cacheControl(cacheControl); } synchronized (requestProperties) { for (Map.Entry<String, String> property : requestProperties.entrySet()) { builder.addHeader(property.getKey(), property.getValue()); } } if (!(position == 0 && length == C.LENGTH_UNBOUNDED)) { String rangeRequest = "bytes=" + position + "-"; if (length != C.LENGTH_UNBOUNDED) { rangeRequest += (position + length - 1); } builder.addHeader("Range", rangeRequest); } builder.addHeader("User-Agent", userAgent); if (!allowGzip) { builder.addHeader("Accept-Encoding", "identity"); } if (dataSpec.postBody != null) { builder.post(RequestBody.create(null, dataSpec.postBody)); } return builder.build(); }
From source file:com.liulishuo.filedownloader.services.FileDownloadRunnable.java
License:Apache License
@Override public void run() { isPending = false;//from ww w . j a v a 2s. c om isRunning = true; int retryingTimes = 0; Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadModel model = this.downloadModel; if (model == null) { FileDownloadLog.e(this, "start runnable but model == null?? %s", getId()); this.downloadModel = helper.find(getId()); if (this.downloadModel == null) { FileDownloadLog.e(this, "start runnable but downloadMode == null?? %s", getId()); return; } model = this.downloadModel; } if (model.getStatus() != FileDownloadStatus.pending) { FileDownloadLog.e(this, "start runnable but status err %s", model.getStatus()); // ??urlpath(????) ?? onError(new RuntimeException(String.format("start runnable but status err %s", model.getStatus()))); return; } // do { long soFar = 0; try { if (model.isCanceled()) { FileDownloadLog.d(this, "already canceled %d %d", model.getId(), model.getStatus()); break; } FileDownloadLog.d(FileDownloadRunnable.class, "start download %s %s", getId(), model.getUrl()); checkIsContinueAvailable(); Request.Builder headerBuilder = new Request.Builder().url(url); addHeader(headerBuilder); headerBuilder.tag(this.getId()); // ?cache?REST? headerBuilder.cacheControl(CacheControl.FORCE_NETWORK); Call call = client.newCall(headerBuilder.get().build()); Response response = call.execute(); final boolean isSucceedStart = response.code() == 200; final boolean isSucceedContinue = response.code() == 206 && isContinueDownloadAvailable; if (isSucceedStart || isSucceedContinue) { long total = downloadTransfer.getTotalBytes(); if (isSucceedStart || total == 0) { total = response.body().contentLength(); } if (isSucceedContinue) { soFar = downloadTransfer.getSoFarBytes(); FileDownloadLog.d(this, "add range %d %d", downloadTransfer.getSoFarBytes(), downloadTransfer.getTotalBytes()); } InputStream inputStream = null; RandomAccessFile accessFile = getRandomAccessFile(isSucceedContinue); try { inputStream = response.body().byteStream(); byte[] buff = new byte[BUFFER_SIZE]; maxNotifyBytes = maxNotifyCounts <= 0 ? -1 : total / maxNotifyCounts; updateHeader(response); onConnected(isSucceedContinue, soFar, total); do { int byteCount = inputStream.read(buff); if (byteCount == -1) { break; } accessFile.write(buff, 0, byteCount); //write buff soFar += byteCount; if (accessFile.length() < soFar) { // ?? throw new RuntimeException( String.format("file be changed by others when downloading %d %d", accessFile.length(), soFar)); } else { onProcess(soFar, total); } if (isCancelled()) { onPause(); return; } } while (true); if (soFar == total) { onComplete(total); // ? break; } else { throw new RuntimeException( String.format("sofar[%d] not equal total[%d]", soFar, total)); } } finally { if (inputStream != null) { inputStream.close(); } if (accessFile != null) { accessFile.close(); } } } else { throw new RuntimeException(String.format("response code error: %d", response.code())); } } catch (Throwable ex) { // TODO ??????? if (autoRetryTimes > retryingTimes++) { // retry onRetry(ex, retryingTimes, soFar); continue; } else { // error onError(ex); break; } } finally { isRunning = false; } } while (true); }
From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java
License:Open Source License
public void requestWalletBalance(final Address... addresses) { backgroundHandler.post(new Runnable() { @Override//w w w . j a va2 s .c om public void run() { org.bitcoinj.core.Context.propagate(Constants.CONTEXT); final HttpUrl.Builder url = HttpUrl.parse(Constants.BITEASY_API_URL).newBuilder(); url.addPathSegment("outputs"); url.addQueryParameter("per_page", "MAX"); url.addQueryParameter("operator", "AND"); url.addQueryParameter("spent_state", "UNSPENT"); for (final Address address : addresses) url.addQueryParameter("address[]", address.toBase58()); log.debug("trying to request wallet balance from {}", url.build()); final Request.Builder request = new Request.Builder(); request.url(url.build()); request.cacheControl(new CacheControl.Builder().noCache().build()); request.header("Accept-Charset", "utf-8"); if (userAgent != null) request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try { final Response response = call.execute(); if (response.isSuccessful()) { final String content = response.body().string(); final JSONObject json = new JSONObject(content); final int status = json.getInt("status"); if (status != 200) throw new IOException("api status " + status + " when fetching unspent outputs"); final JSONObject jsonData = json.getJSONObject("data"); final JSONObject jsonPagination = jsonData.getJSONObject("pagination"); if (!"false".equals(jsonPagination.getString("next_page"))) throw new IOException("result set too big"); final JSONArray jsonOutputs = jsonData.getJSONArray("outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); final Sha256Hash uxtoHash = Sha256Hash.wrap(jsonOutput.getString("transaction_hash")); final int uxtoIndex = jsonOutput.getInt("transaction_index"); final byte[] uxtoScriptBytes = Constants.HEX .decode(jsonOutput.getString("script_pub_key")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); if (tx.getOutputs().size() > uxtoIndex) { // Work around not being able to replace outputs on transactions final List<TransactionOutput> outputs = new ArrayList<TransactionOutput>( tx.getOutputs()); final TransactionOutput dummy = outputs.set(uxtoIndex, output); checkState(dummy.getValue().equals(Coin.NEGATIVE_SATOSHI), "Index %s must be dummy output", uxtoIndex); // Remove and re-add all outputs tx.clearOutputs(); for (final TransactionOutput o : outputs) tx.addOutput(o); } else { // Fill with dummies as needed while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // Add the real output tx.addOutput(output); } } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final int responseCode = response.code(); final String responseMessage = response.message(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } } }); }
From source file:org.opensilk.music.renderer.googlecast.server.ProxyHandler.java
License:Open Source License
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (!HttpMethods.GET.equals(request.getMethod())) { response.sendError(HttpStatus.METHOD_NOT_ALLOWED_405); baseRequest.setHandled(true);//www . j av a2s .com return; } String pathInfo = StringUtils.stripStart(request.getPathInfo(), "/"); Uri contentUri = Uri.parse(CastServerUtil.decodeString(pathInfo)); if (CastServer.DUMP_REQUEST_HEADERS) { StringBuilder reqlog = new StringBuilder(); reqlog.append("Serving artwork uri ").append(contentUri).append("\n Method ") .append(request.getMethod()); for (Enumeration<String> names = request.getHeaderNames(); names.hasMoreElements();) { String name = names.nextElement(); reqlog.append("\n HDR: ").append(name).append(":").append(request.getHeader(name)); } Timber.v(reqlog.toString()); } com.squareup.okhttp.Request.Builder rb = new com.squareup.okhttp.Request.Builder() .url(contentUri.toString()); Track.Res trackRes = mTrackResCache.get(contentUri); //add resource headers Map<String, String> headers = trackRes.getHeaders(); for (Map.Entry<String, String> e : headers.entrySet()) { rb.addHeader(e.getKey(), e.getValue()); } String range = request.getHeader("Range"); if (!StringUtils.isEmpty(range)) { rb.addHeader("Range", range); } String ifnonematch = request.getHeader("if-none-match"); if (!StringUtils.isEmpty(ifnonematch)) { rb.addHeader("if-none-match", ifnonematch); } //dont clog our cache with binaries CacheControl pCC = new CacheControl.Builder().noStore().noCache().build(); rb.cacheControl(pCC); Response pResponse = mOkClient.newCall(rb.get().build()).execute(); if (CastServer.DUMP_REQUEST_HEADERS) { StringBuilder sb = new StringBuilder(); sb.append("Executed proxy GET request uri ").append(contentUri).append("\n Resp: ") .append(pResponse.code()).append(",").append(pResponse.message()); for (String name : pResponse.headers().names()) { sb.append("\n HDR: ").append(name).append(": ").append(pResponse.header(name)); } Timber.v(sb.toString()); } if (!pResponse.isSuccessful()) { response.sendError(pResponse.code(), pResponse.message()); baseRequest.setHandled(true); return; } //build the response String acceptRanges = pResponse.header("Accept-Ranges"); if (!StringUtils.isEmpty(acceptRanges)) { response.addHeader("Accept-Ranges", acceptRanges); } String contentRange = pResponse.header("Content-Range"); if (!StringUtils.isEmpty(contentRange)) { response.addHeader("Content-Range", contentRange); } String contentLen = pResponse.header("Content-Length"); if (!StringUtils.isEmpty(contentLen)) { response.addHeader("Content-Length", contentLen); } String contentType = pResponse.header("Content-Type"); if (StringUtils.isEmpty(contentType)) { contentType = "application/octet-stream"; } response.addHeader("Content-Type", contentType); String etag = pResponse.header("Etag"); if (!StringUtils.isEmpty(etag)) { response.addHeader("Etag", etag); } if (HttpStatus.NOT_MODIFIED_304 == pResponse.code()) { response.flushBuffer(); } else { InputStream in = pResponse.body().byteStream(); try { //XXX out need not be closed OutputStream out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); } } baseRequest.setHandled(true); }
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 {//ww w .j a v a 2 s . 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); } }; }