List of usage examples for com.squareup.okhttp Response isSuccessful
public boolean isSuccessful()
From source file:org.mythtv.services.api.ServerVersionQuery.java
License:Apache License
private static ApiVersion getMythVersion(String baseUri, OkHttpClient client) throws IOException { StringBuilder urlBuilder = new StringBuilder(baseUri); if (!baseUri.endsWith("/")) urlBuilder.append("/"); urlBuilder.append("Myth/GetHostName"); Request request = new Request.Builder().url(urlBuilder.toString()) .addHeader("User-Agent", "MythTv Service API").addHeader("Connection", "Close").build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String serverHeader = response.header(MYTHTV_SERVER_HEADER); if (!Strings.isNullOrEmpty(serverHeader)) { // we have our header get the version. int idx = serverHeader.indexOf(MYTHTV_SERVER_MYTHVERSION); if (idx >= 0) { idx += MYTHTV_SERVER_MYTHVERSION.length(); String version = serverHeader.substring(idx); if (version.contains("0.27")) return ApiVersion.v027; if (version.contains("0.28")) return ApiVersion.v028; }/* w w w . j av a2s .co m*/ } } return ApiVersion.NotSupported; }
From source file:org.mythtv.services.api.ServerVersionQuery.java
License:Apache License
private static boolean isServerReachable(String baseUrl, OkHttpClient client) throws IOException { Request request = new Request.Builder().url(baseUrl) .addHeader("User-Agent", "MythTv Service API Server Reaching").addHeader("Connection", "Close") .build();/* ww w. j ava2s . co m*/ Response response = client.newCall(request).execute(); return response.isSuccessful(); }
From source file:org.openhab.binding.mart.handler.MartHandler.java
License:Open Source License
public void oktrial() { Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); client.newCall(request).enqueue(new Callback() { @Override/* w ww . jav a 2s.c om*/ public void onResponse(Response arg0) throws IOException { // TODO Auto-generated method stub if (arg0.isSuccessful()) { String resp = arg0.body().string(); ByteBuffer byteBuffer = ByteBuffer.allocate(resp.getBytes().length); writer(byteBuffer, datagramChannel); logger.debug(resp); } } @Override public void onFailure(Request arg0, IOException arg1) { // TODO Auto-generated method stub } }); }
From source file:org.opensilk.music.artwork.fetcher.ArtworkFetcherManager.java
License:Open Source License
private Observable<Bitmap> createImageObservable(final String url, final ArtInfo artInfo) { return Observable.create(new Observable.OnSubscribe<Bitmap>() { @Override/*from w ww .ja va 2 s. com*/ public void call(Subscriber<? super Bitmap> subscriber) { if (subscriber.isUnsubscribed()) { return; } InputStream is = null; try { //We don't want okhttp clogging its cache with these images CacheControl cc = new CacheControl.Builder().noStore().build(); Request req = new Request.Builder().url(url).get().cacheControl(cc).build(); Response response = mOkHttpClient.newCall(req).execute(); if (response.isSuccessful()) { is = response.body().byteStream(); Bitmap bitmap = decodeBitmap(is, artInfo); if (bitmap != null && !subscriber.isUnsubscribed()) { subscriber.onNext(bitmap); subscriber.onCompleted(); return; } // else fall } // else fall if (!subscriber.isUnsubscribed()) { subscriber.onError(new Exception("unable to decode " + "bitmap for " + url)); } } catch (IOException | OutOfMemoryError e) { if (!subscriber.isUnsubscribed()) subscriber.onError(e); } finally { IOUtils.closeQuietly(is); } } }); }
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);//from w ww. jav a 2 s . co m 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.runbuddy.libtomahawk.infosystem.hatchet.Store.java
License:Open Source License
public JsonElement get(JsonObject object, String memberName) throws IOException { JsonElement element = object.get(memberName); if (element == null) { JsonObject links = object.getAsJsonObject("links"); if (links != null && links.has(memberName)) { Request request = new Request.Builder().url(HATCHET_BASE_URL + links.get(memberName).getAsString()) .build();//from ww w . j a v a 2s. co m Log.d(TAG, "following link: " + request.urlString()); Response response = mOkHttpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("API request with URL '" + request.urlString() + "' not successful. Code was " + response.code()); } try { element = GsonHelper.get().fromJson(response.body().charStream(), JsonElement.class); } catch (JsonIOException | JsonSyntaxException e) { throw new IOException(e); } finally { response.body().close(); } } } return element; }
From source file:org.sonar.runner.impl.ServerConnection.java
License:Open Source License
/** * @throws IOException if connectivity error/timeout (network) * @throws IllegalStateException if HTTP code is different than 2xx *///from w w w .j a v a 2 s . com private ResponseBody callUrl(String url) throws IOException, IllegalStateException { Request request = new Request.Builder().url(url).addHeader("User-Agent", userAgent).get().build(); Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IllegalStateException(format("Status returned by url [%s] is not valid: [%s]", response.request().url(), response.code())); } return response.body(); }
From source file:org.sufficientlysecure.keychain.keyimport.FacebookKeyserver.java
License:Open Source License
private String query(String fbUsername) throws QueryFailedException { try {/*from w w w. j ava 2 s . c om*/ String request = String.format(FB_KEY_URL_FORMAT, fbUsername); Log.d(Constants.TAG, "fetching from Facebook with: " + request + " proxy: " + mProxy); OkHttpClient client = new OkHttpClient(); client.setProxy(mProxy); URL url = new URL(request); Response response = client.newCall(new Request.Builder().url(url).build()).execute(); // contains body both in case of success or failure String responseBody = response.body().string(); if (response.isSuccessful()) { return responseBody; } else { // probably a 404 indicating that the key does not exist throw new QueryFailedException("key for " + fbUsername + " not found on Facebook"); } } catch (IOException e) { Log.e(Constants.TAG, "IOException at Facebook key download", e); throw new QueryFailedException("Cannot connect to Facebook. " + "Check your Internet connection!" + (mProxy == Proxy.NO_PROXY ? "" : " Using proxy " + mProxy)); } }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyserver.java
License:Apache License
private String query(String request, @NonNull Proxy proxy) throws QueryFailedException, HttpError { try {/*from w w w. j a v a 2 s .com*/ URL url = new URL(getUrlPrefix() + mHost + ":" + mPort + request); Log.d(Constants.TAG, "hkp keyserver query: " + url + " Proxy: " + proxy); OkHttpClient client = getClient(url, proxy); Response response = client.newCall(new Request.Builder().url(url).build()).execute(); String responseBody = response.body().string(); // contains body both in case of success or failure if (response.isSuccessful()) { return responseBody; } else { throw new HttpError(response.code(), responseBody); } } catch (IOException e) { Log.e(Constants.TAG, "IOException at HkpKeyserver", e); throw new QueryFailedException( "Keyserver '" + mHost + "' is unavailable. Check your Internet connection!" + (proxy == Proxy.NO_PROXY ? "" : " Using proxy " + proxy)); } }
From source file:p1.nd.khan.jubair.mohammadd.popularmovies.sync.MovieSyncAdapter.java
License:Apache License
/** * Method to fetch the movie details from server. * * @param pSortOrder : user preferred order for movie display. * @param pPageNo : page number to fetch the record. *///w w w.j a v a2 s.com private void fetchMdbMovie(String pSortOrder, int pPageNo) { OkHttpClient client = new OkHttpClient(); String movieURL = UrlFormatter(pSortOrder, pPageNo); Log.v(LOG_TAG, "URL:" + movieURL); Request request = new Request.Builder().url(movieURL).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e(LOG_TAG, "==onFailure[fetchMdbMovie]:", e); return; } @Override public void onResponse(Response response) throws IOException { try { String jsonData = response.body().string(); if (response.isSuccessful()) { insertMovieContentValues(jsonData); } } catch (IOException | JSONException e) { Log.e(LOG_TAG, "IOException | JSONException: Exception caught: ", e); return; } } }); }