List of usage examples for com.squareup.okhttp Response isSuccessful
public boolean isSuccessful()
From source file:inforuh.eventfinder.sync.SyncAdapter.java
License:Open Source License
@Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Request failed"); handleResponse(response.body().string()); }
From source file:io.fabric8.docker.client.impl.EventHandle.java
License:Apache License
@Override public InputStream getOutput() { try {/* w w w .j av a 2 s . c om*/ if (latch.await(timeoutMillis, TimeUnit.MILLISECONDS)) { Throwable t = error.get(); Response r = response.get(); if (t != null) { throw DockerClientException.launderThrowable(t); } else if (r == null) { throw new DockerClientException("Response not available"); } else if (!r.isSuccessful()) { throw new DockerClientException(r.message()); } else if (pin == null) { throw new DockerClientException( "InputStream not available. Have you used redirectingOutput()?"); } else { return pin; } } else { throw new DockerClientException("Timed out waiting for response"); } } catch (InterruptedException e) { try { close(); } catch (IOException ioe) { throw DockerClientException.launderThrowable(e); } finally { Thread.currentThread().interrupt(); } } throw new DockerClientException("Could not obtain stream"); }
From source file:io.fabric8.docker.client.impl.ImageNamedOperationImpl.java
License:Apache License
public Boolean load(String path) { try {// www .j a v a 2 s. c o m StringBuilder sb = new StringBuilder() .append(URLUtils.join(getRootUrl().toString(), LOAD_OPERATION).toString()); RequestBody body = RequestBody.create(MEDIA_TYPE_TAR, new File(path)); Request request = new Request.Builder().post(body).url(sb.toString()).build(); Response response = client.newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.docker.client.impl.ImageOperationImpl.java
License:Apache License
public Boolean load(String path) { try {// ww w . j a v a2s. co m StringBuilder sb = new StringBuilder() .append(URLUtils.join(getRootUrl().toString(), "load").toString()); RequestBody body = RequestBody.create(MEDIA_TYPE_TAR, new File(path)); Request request = new Request.Builder().post(body).url(sb.toString()).build(); Response response = client.newCall(request).execute(); return response.isSuccessful(); } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.kubernetes.client.internal.SSLUtils.java
License:Apache License
public static boolean isHttpsAvailable(Config config) { Config sslConfig = new ConfigBuilder(config) .withMasterUrl(Config.HTTPS_PROTOCOL_PREFIX + config.getMasterUrl()).withRequestTimeout(1000) .withConnectionTimeout(1000).build(); OkHttpClient client = HttpClientUtils.createHttpClient(config); try {/*from www . j av a 2 s .c o m*/ Request request = new Request.Builder().get().url(sslConfig.getMasterUrl()).build(); Response response = client.newCall(request).execute(); try (ResponseBody body = response.body()) { return response.isSuccessful(); } } catch (Throwable t) { LOG.warn("SSL handshake failed. Falling back to insecure connection."); } finally { if (client != null && client.getConnectionPool() != null) { client.getConnectionPool().evictAll(); } } return false; }
From source file:io.kubernetes.client.util.Watch.java
License:Apache License
/** * Creates a watch on a TYPENAME (T) using an API Client and a Call object. * @param client the API client/*w ww .j a v a 2 s . co m*/ * @param call the call object returned by api.{ListOperation}Call(...) * method. Make sure watch flag is set in the call. * @param watchType The type of the WatchResponse<T>. Use something like * new TypeToken<Watch.Response<TYPENAME>>(){}.getType() * @param <T> TYPENAME. * @return Watch object on TYPENAME * @throws ApiException on IO exceptions. */ public static <T> Watch<T> createWatch(ApiClient client, Call call, Type watchType) throws ApiException { try { com.squareup.okhttp.Response response = call.execute(); if (!response.isSuccessful()) { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } return new Watch<>(client.getJSON(), response.body(), watchType); } catch (IOException e) { throw new ApiException(e); } }
From source file:io.macgyver.neorx.rest.NeoRxClient.java
License:Apache License
public boolean checkConnection() { try {//from w w w . j a v a 2 s . c o m Response r = getClient() .newCall(injectCredentials(new Request.Builder()).url(getUrl() + "/db/data/").build()) .execute(); if (r.isSuccessful()) { r.body().close(); return true; } } catch (IOException | RuntimeException e) { logger.warn(e.toString()); } return false; }
From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java
License:Apache License
public Response execute(RequestBuilder b) { try {//from w ww . jav a 2 s . co m String method = b.getMethod(); Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method argument must be passed"); String url = null; Response resp; String format = b.getParams().getOrDefault("format", "xml"); b = b.param("format", format); if (!b.hasBody()) { url = formatUrl(b.getParams(), format); FormEncodingBuilder fb = new FormEncodingBuilder().add("session_id", getAuthToken()); for (Map.Entry<String, String> entry : b.getParams().entrySet()) { if (!entry.getValue().equals("format")) { fb = fb.add(entry.getKey(), entry.getValue()); } } resp = getClient().newCall(new Request.Builder().url(getUrl()).post(fb.build()).build()).execute(); } else if (b.getXmlBody().isPresent()) { b = b.param("format", "xml"); url = formatUrl(b.getParams(), "xml"); String bodyAsString = new XMLOutputter(Format.getRawFormat()).outputString(b.getXmlBody().get()); final MediaType XML = MediaType.parse("text/xml"); resp = getClient().newCall(new Request.Builder().url(url) .post(RequestBody.create(XML, bodyAsString)).header("Content-Type", "text/xml").build()) .execute(); } else if (b.getJsonBody().isPresent()) { b = b.param("format", "json"); url = formatUrl(b.getParams(), "json"); String bodyAsString = mapper.writeValueAsString(b.getJsonBody().get()); final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); resp = getClient().newCall(new Request.Builder().url(url).post( RequestBody.create(JSON, bodyAsString)).header("Content-Type", "application/json").build()) .execute(); } else { throw new UnsupportedOperationException("body type not supported"); } // the A10 API rather stupidly uses 200 responses even when there is // an error if (!resp.isSuccessful()) { logger.warn("response code={}", resp.code()); } return resp; } catch (IOException e) { throw new ElbException(e); } }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Executes given request parameters./*w w w.java 2s . c o m*/ * * @param method HTTP method. * @param region Amazon S3 region of the bucket. * @param bucketName Bucket name. * @param objectName Object name in 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 HttpResponse execute(Method method, String region, String bucketName, String objectName, Map<String, String> headerMap, Map<String, String> queryParamMap, String contentType, Object body, int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Request request = createRequest(method, bucketName, objectName, region, headerMap, queryParamMap, contentType, body, length); if (this.accessKey != null && this.secretKey != null) { request = Signer.signV4(request, region, accessKey, secretKey); } if (this.traceStream != null) { this.traceStream.println("---------START-HTTP---------"); String encodedPath = request.httpUrl().encodedPath(); String encodedQuery = request.httpUrl().encodedQuery(); if (encodedQuery != null) { encodedPath += "?" + encodedQuery; } this.traceStream.println(request.method() + " " + encodedPath + " HTTP/1.1"); String headers = request.headers().toString().replaceAll("Signature=([0-9a-f]+)", "Signature=*REDACTED*"); this.traceStream.println(headers); } Response response = this.httpClient.newCall(request).execute(); if (response == null) { if (this.traceStream != null) { this.traceStream.println("<NO RESPONSE>"); this.traceStream.println(END_HTTP); } throw new NoResponseException(); } if (this.traceStream != null) { this.traceStream.println(response.protocol().toString().toUpperCase() + " " + response.code()); this.traceStream.println(response.headers()); } ResponseHeader header = new ResponseHeader(); HeaderParser.set(response.headers(), header); if (response.isSuccessful()) { if (this.traceStream != null) { this.traceStream.println(END_HTTP); } return new HttpResponse(header, response); } ErrorResponse errorResponse = null; // HEAD returns no body, and fails on parseXml if (!method.equals(Method.HEAD)) { try { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } errorResponse = new ErrorResponse(new StringReader(errorXml)); if (this.traceStream != null) { this.traceStream.println(errorXml); } } finally { response.body().close(); } } if (this.traceStream != null) { this.traceStream.println(END_HTTP); } if (errorResponse == null) { ErrorCode ec; switch (response.code()) { case 400: ec = ErrorCode.INVALID_URI; break; case 404: if (objectName != null) { ec = ErrorCode.NO_SUCH_KEY; } else if (bucketName != null) { ec = ErrorCode.NO_SUCH_BUCKET; } else { ec = ErrorCode.RESOURCE_NOT_FOUND; } break; case 501: case 405: ec = ErrorCode.METHOD_NOT_ALLOWED; break; case 409: if (bucketName != null) { ec = ErrorCode.NO_SUCH_BUCKET; } else { ec = ErrorCode.RESOURCE_CONFLICT; } break; case 403: ec = ErrorCode.ACCESS_DENIED; break; default: throw new InternalException("unhandled HTTP code " + response.code() + ". Please report this issue at " + "https://github.com/minio/minio-java/issues"); } errorResponse = new ErrorResponse(ec, bucketName, objectName, request.httpUrl().encodedPath(), header.xamzRequestId(), header.xamzId2()); } // invalidate region cache if needed if (errorResponse.errorCode() == ErrorCode.NO_SUCH_BUCKET) { BucketRegionCache.INSTANCE.remove(bucketName); // TODO: handle for other cases as well // observation: on HEAD of a bucket with wrong region gives 400 without body } throw new ErrorResponseException(errorResponse, response); }
From source file:io.morea.handy.android.SendLogTask.java
License:Apache License
private Set<UUID> sendEvents(final List<Event> events) throws Exception { final Set<UUID> sentEvents = new HashSet<>(); if (events.isEmpty()) { return sentEvents; }/*from w ww.j a va 2 s .c om*/ log.log(Level.INFO, String.format("Sending %d events to server %s.", events.size(), configuration.getRemoteEndpoint())); final Request request = new Request.Builder().url(configuration.getRemoteEndpoint()) .post(RequestBody.create(MEDIA_TYPE_JSON, gson.toJson(events))) .addHeader("User-Agent", Constant.USER_AGENT).build(); final Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { log.log(Level.SEVERE, String.format("Failed to post events to server, response status is %d.", response.code())); return sentEvents; } for (Event e : events) { log.log(Level.FINE, String.format("Event %s successfully sent to server.", e.getIdentifier())); sentEvents.add(e.getIdentifier()); } return sentEvents; }