List of usage examples for com.squareup.okhttp OkHttpClient newCall
public Call newCall(Request request)
From source file:com.google.example.gcmnetworkmanagerquickstart.MyTaskService.java
License:Open Source License
private int fetchUrl(OkHttpClient client, String url) { Request request = new Request.Builder().url(url).build(); try {/*from w ww . ja v a 2 s .com*/ Response response = client.newCall(request).execute(); Log.d(TAG, "fetchUrl:response:" + response.body().string()); if (response.code() != 200) { return GcmNetworkManager.RESULT_FAILURE; } } catch (IOException e) { Log.e(TAG, "fetchUrl:error" + e.toString()); return GcmNetworkManager.RESULT_FAILURE; } return GcmNetworkManager.RESULT_SUCCESS; }
From source file:com.google.maps.internal.OkHttpPendingResult.java
License:Open Source License
/** * @param request HTTP request to execute. * @param client The client used to execute the request. * @param responseClass Model class to unmarshal JSON body content. * @param fieldNamingPolicy FieldNamingPolicy for unmarshaling JSON. * @param errorTimeOut Number of milliseconds to re-send erroring requests. *//*from w ww.j a va 2 s.co m*/ public OkHttpPendingResult(Request request, OkHttpClient client, Class<R> responseClass, FieldNamingPolicy fieldNamingPolicy, long errorTimeOut) { this.request = request; this.client = client; this.responseClass = responseClass; this.fieldNamingPolicy = fieldNamingPolicy; this.errorTimeOut = errorTimeOut; this.call = client.newCall(request); }
From source file:com.google.minijoe.sys.Eval.java
License:Apache License
public void evalNative(int index, JsArray stack, int sp, int parCount) { switch (index) { case ID_HTTP_GET: try {/* ww w. j a va 2s .c o m*/ String url = stack.getString(sp + 2); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); stack.setObject(sp, response.body().string()); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_POST_JSON: try { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), stack.getString(sp + 3)); Request request = new Request.Builder().url(stack.getString(sp + 2)).post(body).build(); Response response = client.newCall(request).execute(); stack.setObject(sp, response.body().string()); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_CRAWLER: try { Crawler.startCrawler(stack.getString(sp + 2)); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_CURL: new Thread(new Curl()).start(); break; case ID_EXTRACT_HTML: try { Readability readability = new Readability(new URL(stack.getString(sp + 2)), stack.getInt(sp + 3)); readability.init(); stack.setObject(sp, readability.outerHtml()); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } break; case ID_EVAL: try { stack.setObject(sp, eval(stack.getString(sp + 2), stack.isNull(sp + 3) ? stack.getJsObject(sp) : stack.getJsObject(sp + 3))); } catch (Exception e) { throw new RuntimeException("" + e); } break; case ID_COMPILE: try { File file = new File(stack.getString(sp + 2)); DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] data = new byte[(int) file.length()]; dis.readFully(data); String code = new String(data, "UTF-8"); Eval.compile(code, System.out); dis.close(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LOAD: try { File file = new File(stack.getString(sp + 2)); DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] data = new byte[(int) file.length()]; dis.readFully(data); String code = new String(data, "UTF-8"); //xxx.js Eval.eval(code, Eval.createGlobal()); dis.close(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_GEN_SITEMAP: try { // create web sitemap for web http://www.javavids.com WebSitemapGenerator webSitemapGenerator = new WebSitemapGenerator("http://www.javavids.com"); // add some URLs webSitemapGenerator.addPage(new WebPage().setName("index.php").setPriority(1.0) .setChangeFreq(ChangeFreq.NEVER).setLastMod(new Date())); webSitemapGenerator.addPage(new WebPage().setName("latest.php")); webSitemapGenerator.addPage(new WebPage().setName("contact.php")); // generate sitemap and save it to file /var/www/sitemap.xml File file = new File("/var/www/sitemap.xml"); webSitemapGenerator.constructAndSaveSitemap(file); // inform Google that this sitemap has changed webSitemapGenerator.pingGoogle(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_WHOIS: try { stack.setObject(sp, Whois.getRawWhoisResults(stack.getString(sp + 2))); } catch (WhoisException e) { stack.setObject(sp, "Whois Exception " + e.getMessage()); } catch (HostNameValidationException e) { stack.setObject(sp, "Whois host name invalid " + e.getMessage()); } break; case ID_PAGERANK: stack.setObject(sp, PageRank.getPR(stack.getString(sp + 2))); break; case ID_SEND_TWITTER: try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out .print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(stack.getString(sp + 2)); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } break; case ID_EXTRACT_TEXT: try { String url = stack.getString(sp + 2); String selector = stack.getString(sp + 3); Document doc = Jsoup.connect(url).userAgent("okhttp").timeout(5 * 1000).get(); HtmlToPlainText formatter = new HtmlToPlainText(); if (selector != null) { Elements elements = doc.select(selector); StringBuffer sb = new StringBuffer(); for (Element element : elements) { String plainText = formatter.getPlainText(element); sb.append(plainText); } stack.setObject(sp, sb.toString()); } else { stack.setObject(sp, formatter.getPlainText(doc)); } } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LIST_LINKS: try { String url = stack.getString(sp + 2); print("Fetching %s...", url); Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); Elements media = doc.select("[src]"); Elements imports = doc.select("link[href]"); print("\nMedia: (%d)", media.size()); for (Element src : media) { if (src.tagName().equals("img")) print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"), trim(src.attr("alt"), 20)); else print(" * %s: <%s>", src.tagName(), src.attr("abs:src")); } print("\nImports: (%d)", imports.size()); for (Element link : imports) { print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel")); } print("\nLinks: (%d)", links.size()); for (Element link : links) { print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); } } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LOG: log.info(stack.getString(sp + 2)); break; case ID_SEND_MAIL: try { // put your e-mail address here final String yourAddress = "guilherme.@gmail.com"; // configure programatically your mail server info EmailTransportConfiguration.configure("smtp.server.com", true, false, "username", "password"); // and go! new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress) .withSubject("Fluent Mail API").withAttachment("file_name").withBody("Demo message").send(); } catch (Exception ex) { stack.setObject(sp, "[ERROR]" + ex.getMessage()); } break; case ID_SNAPPY: try { String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of " + "Snappy, a fast compresser/decompresser."; byte[] compressed = Snappy.compress(input.getBytes("UTF-8")); byte[] uncompressed = Snappy.uncompress(compressed, 0, compressed.length); String result = new String(uncompressed, "UTF-8"); System.out.println(result); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_OPENBROWSER: new Thread(new Runnable() { public void run() { openBrowser(); } }).start(); break; case ID_HELP: Enumeration ex = this.keys(); while (ex.hasMoreElements()) { String key = (String) ex.nextElement(); Object val = this.getRawInPrototypeChain(key); if (val instanceof JsFunction) { System.out.println(key + "---" + ((JsFunction) val).description); } else { System.out.println(key + "---" + val); } } break; default: super.evalNative(index, stack, sp, parCount); } }
From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java
License:Apache License
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try {/*from w w w . j av a2 s . com*/ String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); /* * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port * by checking it only has a : as part of http:// */ if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } }
From source file:com.gzsll.downloads.DownloadThread.java
License:Apache License
/** * Send the request to the server, handling any I/O exceptions. *//*from w ww . j a v a 2 s .co m*/ private Response sendRequest(State state, OkHttpClient client, Request request) throws StopRequest { try { return client.newCall(request).execute(); } catch (IOException ex) { logNetworkState(); throw new StopRequest(getFinalStatusForHttpError(state), "while trying to execute request: " + ex.toString(), ex); } }
From source file:com.heroiclabs.sdk.android.HttpClient.java
License:Apache License
/** {@inheritDoc} */ public <T> Deferred<Response<T>> execute(final @NonNull Request<T> request) { final Deferred<Response<T>> deferred = new Deferred<>(); // Select the host, implicitly only allow HTTPS. HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("https") .host(getServer(request.getDestination())); // Encode and add the path elements. for (final String p : getPath(request.getRequestType(), request.getIdentifiers())) { urlBuilder = urlBuilder.addPathSegment(p); }/*from w ww . j a v a 2 s.c o m*/ // Encode and add the query parameters, toString() values as we go. for (final Map.Entry<String, ?> e : request.getParameters().entrySet()) { urlBuilder = urlBuilder.addQueryParameter(e.getKey(), e.getValue().toString()); } final HttpUrl url = urlBuilder.build(); final String token = request.getSession() == null ? "" : request.getSession().getToken(); final String authorization = "Basic " + ByteString.of((apiKey + ":" + token).getBytes()).base64(); final String contentType = "application/json"; final String body = getBody(request.getRequestType(), request.getEntity()); // Construct the HTTP request. final com.squareup.okhttp.Request httpRequest = new com.squareup.okhttp.Request.Builder().url(url) .method(getMethod(request.getRequestType()), body == null ? null : RequestBody.create(MediaType.parse(contentType), body)) .header("User-Agent", USER_AGENT).header("Content-Type", contentType).header("Accept", contentType) .header("Authorization", authorization).build(); // Prepare a HTTP client instance to execute against. final OkHttpClient client = this.client.clone(); // Interceptors fire in the order they're declared. // Note: Compress first, so we don't re-compress for retried requests. if (this.compressRequests) { client.interceptors().add(GzipRequestInterceptor.INSTANCE); } final int maxAttempts = request.getMaxAttempts() < 1 ? this.maxAttempts : request.getMaxAttempts(); client.interceptors().add(new RetryInterceptor(maxAttempts)); // Log the outgoing request. if (log.isDebugEnabled()) { log.debug("Request: Method{" + httpRequest.method() + "} URL{" + httpRequest.urlString() + "} Headers{" + httpRequest.headers().toString() + "} Body{" + body + "}"); } // Send the request and retrieve a response. client.newCall(httpRequest).enqueue(new Callback() { @Override public void onFailure(final com.squareup.okhttp.Request httpRequest, final IOException e) { // Log the request failure reason. if (log.isDebugEnabled()) { log.debug("Request Failed", e); } deferred.callback(new ErrorResponse(e.getMessage(), e, request)); } @Override public void onResponse(final @NonNull com.squareup.okhttp.Response httpResponse) throws IOException { switch (httpResponse.code()) { // Good response with body. case HttpURLConnection.HTTP_OK: final String responseBody = httpResponse.body().string(); // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "} Body{" + responseBody + "}"); } final T entity = codec.deserialize(responseBody, request.getResponseType()); deferred.callback(new SuccessResponse<>(request, httpResponse.code(), responseBody, entity)); break; // Good response, no body. case HttpURLConnection.HTTP_NO_CONTENT: case HttpURLConnection.HTTP_CREATED: // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "}"); } deferred.callback(new SuccessResponse<>(request, httpResponse.code(), null, null)); break; // Error response. default: final String errorBody = httpResponse.body().string(); // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Error: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "} Body{" + errorBody + "}"); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") final ErrorDetails error = errorBody.isEmpty() ? new ErrorDetails(httpResponse.code(), httpResponse.message() == null ? "unknown" : httpResponse.message(), null) : codec.deserialize(errorBody, ErrorDetails.class); deferred.callback(new ErrorResponse(error.getMessage(), error, request)); } // Indicate that application-layer response processing is complete. httpResponse.body().close(); } }); return deferred; }
From source file:com.hippo.network.DownloadClient.java
License:Apache License
public static boolean execute(DownloadRequest request) { OnDownloadListener listener = request.mListener; OkHttpClient okHttpClient = request.mOkHttpClient; UniFile uniFile = null;//from w w w. j a va 2 s . c o m OutputStreamPipe osPipe = null; try { Call call = okHttpClient.newCall(new GoodRequestBuilder(request.mUrl).build()); request.mCall = call; // Listener if (listener != null) { listener.onStartDownloading(); } Response response = call.execute(); ResponseBody body = response.body(); // Check response code int responseCode = response.code(); if (responseCode >= 400) { throw new ResponseCodeException(responseCode); } osPipe = request.mOSPipe; if (osPipe == null) { String extension; String name; String dispositionFilename = getFilenameFromContentDisposition( response.header("Content-Disposition")); if (dispositionFilename != null) { name = FileUtils.getNameFromFilename(dispositionFilename); extension = FileUtils.getExtensionFromFilename(dispositionFilename); } else { name = Utilities.getNameFromUrl(request.mUrl); extension = Utilities.getExtensionFromMimeType(response.header("Content-Type")); if (extension == null) { extension = MimeTypeMap.getFileExtensionFromUrl(request.mUrl); } } String filename; if (listener != null) { filename = listener.onFixname(name, extension, request.mFilename); } else { filename = request.mFilename; } request.mFilename = filename; // Use Temp filename uniFile = request.mDir.createFile(FileUtils.ensureFilename(filename + ".download")); if (uniFile == null) { // Listener if (listener != null) { listener.onFailed(new IOException("Can't create file " + filename)); } return false; } osPipe = new UniFileOutputStreamPipe(uniFile); } osPipe.obtain(); long contentLength = body.contentLength(); // Listener if (listener != null) { listener.onConnect(contentLength); } long receivedSize = transferData(body.byteStream(), osPipe.open(), listener); if (contentLength > 0 && contentLength != receivedSize) { throw new IOException( "contentLength is " + contentLength + ", but receivedSize is " + receivedSize); } // Rename if (uniFile != null && request.mFilename != null) { uniFile.renameTo(request.mFilename); } // Listener if (listener != null) { listener.onSucceed(); } return true; } catch (Exception e) { // remove download failed file if (uniFile != null) { uniFile.delete(); } if (listener != null) { listener.onFailed(e); } return false; } finally { if (osPipe != null) { osPipe.close(); osPipe.release(); } } }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareGetCookie(OkHttpClient okHttpClient) { String url = ACUrl.API_GET_COOKIE; Log.d(TAG, url);/* w w w . j av a2s . c om*/ Request request = new GoodRequestBuilder(url).build(); return okHttpClient.newCall(request); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareGetCommonPosts(OkHttpClient okHttpClient) { String url = ACUrl.API_COMMON_POSTS; Log.d(TAG, url);//from w ww. ja v a 2 s . co m Request request = new GoodRequestBuilder(url).build(); return okHttpClient.newCall(request); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareGetForumList(OkHttpClient okHttpClient) { String url = ACUrl.API_GET_FORUM_LIST; Log.d(TAG, url);/*from ww w . jav a2 s . c o m*/ Request request = new GoodRequestBuilder(url).build(); return okHttpClient.newCall(request); }