List of usage examples for com.squareup.okhttp Request.Builder url
HttpUrl url
To view the source code for com.squareup.okhttp Request.Builder url.
Click Source Link
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); 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 {/* w w w. ja v a2 s.c om*/ 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 v a 2 s.com 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; }
From source file:de.schildbach.wallet.ExchangeRatesProvider.java
License:Open Source License
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String source, final String... fields) { final Stopwatch watch = Stopwatch.createStarted(); final Request.Builder request = new Request.Builder(); request.url(url); request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try {/*from ww w.j a v a 2 s . c o m*/ final Response response = call.execute(); if (response.isSuccessful()) { final String content = response.body().string(); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = Strings.emptyToNull(i.next()); if (currencyCode != null && !"timestamp".equals(currencyCode) && !MonetaryFormat.CODE_BTC.equals(currencyCode) && !MonetaryFormat.CODE_MBTC.equals(currencyCode) && !MonetaryFormat.CODE_UBTC.equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { final String rateStr = o.optString(field, null); if (rateStr != null) { try { final Fiat rate = Fiat.parseFiat(currencyCode, rateStr); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate( new org.bitcoinj.utils.ExchangeRate(rate), source)); break; } } catch (final NumberFormatException x) { log.warn("problem fetching {} exchange rate from {}: {}", currencyCode, url, x.getMessage()); } } } } } watch.stop(); log.info("fetched exchange rates from {}, {} chars, took {}", url, content.length(), watch); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", response.code(), url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } return null; }
From source file:de.schildbach.wallet.ui.AlertDialogsFragment.java
License:Open Source License
@Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); log.debug("querying \"{}\"...", versionUrl); final Request.Builder request = new Request.Builder(); request.url(versionUrl); request.header("Accept-Charset", "utf-8"); final String userAgent = application.httpUserAgent(); if (userAgent != null) request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); backgroundHandler.post(new Runnable() { @Override/*from w ww. j a v a 2 s . co m*/ public void run() { boolean abort = false; try { final Response response = call.execute(); if (response.isSuccessful()) { final long serverTime = response.headers().getDate("Date").getTime(); try (final BufferedReader reader = new BufferedReader(response.body().charStream())) { abort = handleServerTime(serverTime); while (true) { final String line = reader.readLine(); if (line == null) break; if (line.charAt(0) == '#') continue; final Splitter splitter = Splitter.on('=').trimResults(); final Iterator<String> split = splitter.split(line).iterator(); if (!split.hasNext()) continue; final String key = split.next(); if (!split.hasNext()) { abort = handleLine(key); if (abort) break; continue; } final String value = split.next(); if (!split.hasNext()) { abort = handleProperty(key, value); if (abort) break; continue; } log.info("Ignoring line: {}", line); } } } } catch (final Exception x) { handleException(x); } if (!abort) handleCatchAll(); } }); }
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/*from w w w . j av a 2 s. co m*/ 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:de.schildbach.wallet.util.HttpGetThread.java
License:Open Source License
@Override public void run() { log.debug("querying \"{}\"...", url); final Request.Builder request = new Request.Builder(); request.url(url); request.header("Accept-Charset", "utf-8"); if (userAgent != null) request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try {// ww w. ja v a2 s . c om final Response response = call.execute(); if (response.isSuccessful()) { final long serverTime = response.headers().getDate("Date").getTime(); final BufferedReader reader = new BufferedReader(response.body().charStream()); final String line = reader.readLine().trim(); reader.close(); handleLine(line, serverTime); } } catch (final Exception x) { handleException(x); } }
From source file:feign.okhttp.OkHttpClient.java
License:Apache License
static Request toOkHttpRequest(feign.Request input) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(input.url()); MediaType mediaType = null;/*from w w w .j a va2 s. c om*/ boolean hasAcceptHeader = false; for (String field : input.headers().keySet()) { if (field.equalsIgnoreCase("Accept")) { hasAcceptHeader = true; } for (String value : input.headers().get(field)) { if (field.equalsIgnoreCase("Content-Type")) { mediaType = MediaType.parse(value); if (input.charset() != null) { mediaType.charset(input.charset()); } } else { requestBuilder.addHeader(field, value); } } } // Some servers choke on the default accept string. if (!hasAcceptHeader) { requestBuilder.addHeader("Accept", "*/*"); } RequestBody body = input.body() != null ? RequestBody.create(mediaType, input.body()) : null; requestBuilder.method(input.method(), body); return requestBuilder.build(); }
From source file:info.curtbinder.reefangel.service.ControllerTask.java
License:Creative Commons License
public void run() { // Communicate with controller // clear out the error code on run rapp.clearErrorCode();/*from w w w. j av a 2 s .c om*/ Response response = null; boolean fInterrupted = false; broadcastUpdateStatus(R.string.statusStart); try { URL url = new URL(host.toString()); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(host.getConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(host.getReadTimeout(), TimeUnit.MILLISECONDS); Request.Builder builder = new Request.Builder(); builder.url(url); if (host.isDeviceAuthenticationEnabled()) { String creds = Credentials.basic(host.getWifiUsername(), host.getWifiPassword()); builder.header("Authorization", creds); } Request req = builder.build(); broadcastUpdateStatus(R.string.statusConnect); response = client.newCall(req).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); if (Thread.interrupted()) throw new InterruptedException(); } catch (MalformedURLException e) { rapp.error(1, e, "MalformedURLException"); } catch (SocketTimeoutException e) { rapp.error(5, e, "SocketTimeoutException"); } catch (ConnectException e) { rapp.error(3, e, "ConnectException"); } catch (UnknownHostException e) { String msg = "Unknown Host: " + host.toString(); UnknownHostException ue = new UnknownHostException(msg); rapp.error(4, ue, "UnknownHostException"); } catch (EOFException e) { EOFException eof = new EOFException(rapp.getString(R.string.errorAuthentication)); rapp.error(3, eof, "EOFException"); } catch (IOException e) { rapp.error(3, e, "IOException"); } catch (InterruptedException e) { fInterrupted = true; } processResponse(response, fInterrupted); }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Creates Request object for given request parameters. * * @param method HTTP method.// w ww. ja v a 2 s. c o m * @param bucketName Bucket name. * @param objectName Object name in the bucket. * @param region Amazon S3 region of the bucket. * @param headerMap Map of HTTP headers for the request. * @param queryParamMap Map of HTTP query parameters of the request. * @param contentType Content type of the request body. * @param body HTTP request body. * @param length Length of HTTP request body. */ private Request createRequest(Method method, String bucketName, String objectName, String region, Map<String, String> headerMap, Map<String, String> queryParamMap, final String contentType, final Object body, final int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException { if (bucketName == null && objectName != null) { throw new InvalidBucketNameException(NULL_STRING, "null bucket name for object '" + objectName + "'"); } HttpUrl.Builder urlBuilder = this.baseUrl.newBuilder(); if (bucketName != null) { checkBucketName(bucketName); String host = this.baseUrl.host(); if (host.equals(S3_AMAZONAWS_COM)) { // special case: handle s3.amazonaws.com separately if (region != null) { host = AwsS3Endpoints.INSTANCE.endpoint(region); } boolean usePathStyle = false; if (method == Method.PUT && objectName == null && queryParamMap == null) { // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com usePathStyle = true; } else if (queryParamMap != null && queryParamMap.containsKey("location")) { // use path style for location query usePathStyle = true; } else if (bucketName.contains(".") && this.baseUrl.isHttps()) { // use path style where '.' in bucketName causes SSL certificate validation error usePathStyle = true; } if (usePathStyle) { urlBuilder.host(host); urlBuilder.addPathSegment(bucketName); } else { urlBuilder.host(bucketName + "." + host); } } else { urlBuilder.addPathSegment(bucketName); } } if (objectName != null) { for (String pathSegment : objectName.split("/")) { // Limitation: // 1. OkHttp does not allow to add '.' and '..' as path segment. // 2. Its not allowed to add path segment as '/', '//', '/usr' or 'usr/'. urlBuilder.addPathSegment(pathSegment); } } if (queryParamMap != null) { for (Map.Entry<String, String> entry : queryParamMap.entrySet()) { urlBuilder.addEncodedQueryParameter(Signer.encodeQueryString(entry.getKey()), Signer.encodeQueryString(entry.getValue())); } } RequestBody requestBody = null; if (body != null) { requestBody = new RequestBody() { @Override public MediaType contentType() { if (contentType != null) { return MediaType.parse(contentType); } else { return MediaType.parse("application/octet-stream"); } } @Override public long contentLength() { if (body instanceof InputStream || body instanceof RandomAccessFile || body instanceof byte[]) { return length; } if (length == 0) { return -1; } else { return length; } } @Override public void writeTo(BufferedSink sink) throws IOException { byte[] data = null; if (body instanceof InputStream) { InputStream stream = (InputStream) body; sink.write(Okio.source(stream), length); } else if (body instanceof RandomAccessFile) { RandomAccessFile file = (RandomAccessFile) body; sink.write(Okio.source(Channels.newInputStream(file.getChannel())), length); } else if (body instanceof byte[]) { sink.write(data, 0, length); } else { sink.writeUtf8(body.toString()); } } }; } HttpUrl url = urlBuilder.build(); // urlBuilder does not encode some characters properly for Amazon S3. // Encode such characters properly here. List<String> pathSegments = url.encodedPathSegments(); urlBuilder = url.newBuilder(); for (int i = 0; i < pathSegments.size(); i++) { urlBuilder.setEncodedPathSegment(i, pathSegments.get(i).replaceAll("\\!", "%21").replaceAll("\\$", "%24").replaceAll("\\&", "%26") .replaceAll("\\'", "%27").replaceAll("\\(", "%28").replaceAll("\\)", "%29") .replaceAll("\\*", "%2A").replaceAll("\\+", "%2B").replaceAll("\\,", "%2C") .replaceAll("\\:", "%3A").replaceAll("\\;", "%3B").replaceAll("\\=", "%3D") .replaceAll("\\@", "%40").replaceAll("\\[", "%5B").replaceAll("\\]", "%5D")); } url = urlBuilder.build(); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); requestBuilder.method(method.toString(), requestBody); if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { requestBuilder.header(entry.getKey(), entry.getValue()); } } String sha256Hash = null; String md5Hash = null; if (this.accessKey != null && this.secretKey != null) { // No need to compute sha256 if endpoint scheme is HTTPS. Issue #415. if (url.isHttps()) { sha256Hash = "UNSIGNED-PAYLOAD"; if (body instanceof BufferedInputStream) { md5Hash = Digest.md5Hash((BufferedInputStream) body, length); } else if (body instanceof RandomAccessFile) { md5Hash = Digest.md5Hash((RandomAccessFile) body, length); } else if (body instanceof byte[]) { byte[] data = (byte[]) body; md5Hash = Digest.md5Hash(data, length); } } else { if (body == null) { sha256Hash = Digest.sha256Hash(new byte[0]); } else { if (body instanceof BufferedInputStream) { String[] hashes = Digest.sha256md5Hashes((BufferedInputStream) body, length); sha256Hash = hashes[0]; md5Hash = hashes[1]; } else if (body instanceof RandomAccessFile) { String[] hashes = Digest.sha256md5Hashes((RandomAccessFile) body, length); sha256Hash = hashes[0]; md5Hash = hashes[1]; } else if (body instanceof byte[]) { byte[] data = (byte[]) body; sha256Hash = Digest.sha256Hash(data, length); md5Hash = Digest.md5Hash(data, length); } else { sha256Hash = Digest.sha256Hash(body.toString()); } } } } if (md5Hash != null) { requestBuilder.header("Content-MD5", md5Hash); } if (url.port() == 80 || url.port() == 443) { requestBuilder.header("Host", url.host()); } else { requestBuilder.header("Host", url.host() + ":" + url.port()); } requestBuilder.header("User-Agent", this.userAgent); if (sha256Hash != null) { requestBuilder.header("x-amz-content-sha256", sha256Hash); } DateTime date = new DateTime(); requestBuilder.header("x-amz-date", date.toString(DateFormat.AMZ_DATE_FORMAT)); return requestBuilder.build(); }
From source file:microsoft.aspnet.signalr.client.http.android.AndroidOkHttpConnection.java
License:Open Source License
private static com.squareup.okhttp.Request createRequest(Request request) { com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); switch (request.getVerb()) { case Constants.HTTP_GET: okHttpRequestBuilder.get();/*from w ww. j a v a 2s . c om*/ break; case Constants.HTTP_POST: okHttpRequestBuilder.post(RequestBody.create(null, request.getContent())); break; default: throw new IllegalArgumentException(String.format("%s is not GET or POST", request.getVerb())); } for (String key : request.getHeaders().keySet()) { okHttpRequestBuilder.addHeader(key, request.getHeaders().get(key)); } return okHttpRequestBuilder.build(); }