List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
From source file:io.kodokojo.service.marathon.MarathonConfigurationStore.java
License:Open Source License
@Override public boolean storeSSLKeys(String project, String entityName, SSLKeyPair sslKeyPair) { if (isBlank(project)) { throw new IllegalArgumentException("project must be defined."); }/* ww w . j a v a 2s. c o m*/ if (isBlank(entityName)) { throw new IllegalArgumentException("entityName must be defined."); } if (sslKeyPair == null) { throw new IllegalArgumentException("sslKeyPair must be defined."); } Response response = null; try { Writer writer = new StringWriter(); SSLUtils.writeSSLKeyPairPem(sslKeyPair, writer); byte[] certificat = writer.toString().getBytes(); String url = marathonUrl + "/v2/artifacts/ssl/" + project.toLowerCase() + "/" + entityName.toLowerCase() + "/" + project.toLowerCase() + "-" + entityName.toLowerCase() + "-server.pem"; OkHttpClient httpClient = new OkHttpClient(); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("file", project + "-" + entityName + "-server.pem", RequestBody.create(MediaType.parse("application/text"), certificat)) .build(); Request request = new Request.Builder().url(url).post(requestBody).build(); response = httpClient.newCall(request).execute(); int code = response.code(); if (code > 200 && code < 300) { LOGGER.info("Push SSL certificate on marathon url '{}' [content-size={}]", url, certificat.length); } else { LOGGER.error("Fail to push SSL certificate on marathon url '{}' status code {}. Body response:\n{}", url, code, response.body().string()); } return code > 200 && code < 300; } catch (IOException e) { LOGGER.error("Unable to store ssl key for project {} and brick {}", project, entityName, e); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } 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//from w w w . j a v a 2 s .c o 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.core.okhttp.LoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE || (!slf4j.isDebugEnabled())) { return chain.proceed(request); }//from w w w . ja v a2 s . c o m boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; try { RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if (name.equalsIgnoreCase("authorization")) { log(name + ": ************"); } else { // Skip headers from the request body as they are // explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { log(name + ": " + headers.value(i)); } } } if (!logBody || !hasRequestBody) { slf4j.debug("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } log(""); String body = redactRequestBody(buffer.readString(charset)); log(body); log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace } long startNs = System.nanoTime(); Response response = chain.proceed(request); try { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { log("<-- END HTTP"); } else if (!isResponseBodyPrintable(response)) { log("<-- END HTTP (body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(maxPrintableBodySize); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() != 0) { log(""); log(redactResponseBody(buffer.clone().readString(charset))); } log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString()); } return response; }
From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java
License:Apache License
public Response execute(RequestBuilder b) { try {/*from www .j a v a 2s .c o 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.macgyver.test.MockWebServerTest.java
License:Apache License
@Test public void testIt() throws IOException, InterruptedException { // set up mock response mockServer.enqueue(/*from ww w . ja va 2s. c o m*/ new MockResponse().setBody("{\"name\":\"Rob\"}").addHeader("Content-type", "application/json")); // set up client and request OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(mockServer.getUrl("/test").toString()) .post(RequestBody.create(MediaType.parse("application/json"), "{}")) .header("Authorization", Credentials.basic("scott", "tiger")).build(); // make the call Response response = client.newCall(request).execute(); // check the response assertThat(response.code()).isEqualTo(200); assertThat(response.header("content-type")).isEqualTo("application/json"); // check the response body JsonNode n = new ObjectMapper().readTree(response.body().string()); assertThat(n.path("name").asText()).isEqualTo("Rob"); // now make sure that the request was as we exepected it to be RecordedRequest recordedRequest = mockServer.takeRequest(); assertThat(recordedRequest.getPath()).isEqualTo("/test"); assertThat(recordedRequest.getHeader("Authorization")).isEqualTo("Basic c2NvdHQ6dGlnZXI="); }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Executes given request parameters.//from ww w . j a v a2 s. 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; }/*w w w . j a v a 2s .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; }
From source file:io.promagent.it.SpringIT.java
License:Apache License
/** * Run some HTTP queries against a Docker container from image promagent/spring-promagent. * <p/>/* w w w. j a v a 2 s.c o m*/ * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pspring</tt>. */ @Test public void testSpring() throws Exception { OkHttpClient client = new OkHttpClient(); Request metricsRequest = new Request.Builder().url(System.getProperty("promagent.url") + "/metrics") .build(); // Execute two POST requests Response restResponse = client.newCall(makePostRequest("Frodo", "Baggins")).execute(); assertEquals(201, restResponse.code()); restResponse = client.newCall(makePostRequest("Bilbo", "Baggins")).execute(); assertEquals(201, restResponse.code()); // Query Prometheus metrics from promagent Response metricsResponse = client.newCall(metricsRequest).execute(); String[] metricsLines = metricsResponse.body().string().split("\n"); String httpRequestsTotal = Arrays.stream(metricsLines).filter(m -> m.contains("http_requests_total")) .filter(m -> m.contains("method=\"POST\"")).filter(m -> m.contains("path=\"/people\"")) .filter(m -> m.contains("status=\"201\"")).findFirst() .orElseThrow(() -> new Exception("http_requests_total metric not found.")); assertTrue(httpRequestsTotal.endsWith("2.0"), "Value should be 2.0 for " + httpRequestsTotal); String sqlQueriesTotal = Arrays.stream(metricsLines).filter(m -> m.contains("sql_queries_total")) // The following regular expression tests for this string, but allows the parameters 'id', 'fist_name', 'last_name' to change order: // query="insert into person (first_name, last_name, id)" .filter(m -> m.matches( ".*query=\"insert into person \\((?=.*id)(?=.*first_name)(?=.*last_name).*\\) values \\(...\\)\".*")) .filter(m -> m.contains("method=\"POST\"")).filter(m -> m.contains("path=\"/people\"")).findFirst() .orElseThrow(() -> new Exception("sql_queries_total metric not found.")); assertTrue(sqlQueriesTotal.endsWith("2.0"), "Value should be 2.0 for " + sqlQueriesTotal); }
From source file:io.promagent.it.WildflyIT.java
License:Apache License
/** * Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent. * <p/>// w ww .jav a2 s . c om * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>. */ @Test public void testWildfly() throws Exception { OkHttpClient client = new OkHttpClient(); Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members") .build(); // Execute REST call Response restResponse = client.newCall(restRequest).execute(); Assertions.assertEquals(restResponse.code(), 200); Assertions.assertTrue(restResponse.body().string().contains("John Smith")); Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric assertMetrics(client, "1.0"); // Execute REST call again restResponse = client.newCall(restRequest).execute(); Assertions.assertEquals(restResponse.code(), 200); Assertions.assertTrue(restResponse.body().string().contains("John Smith")); Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric assertMetrics(client, "2.0"); }
From source file:io.sidecar.client.SidecarRequest.java
License:Apache License
protected SidecarResponse send(Request httpReq) { try {//from ww w. j av a2 s . com Response resp = httpClient.newCall(httpReq).execute(); return new SidecarResponse(resp.code(), resp.body().string()); } catch (Exception e) { throw new RuntimeException(e); } }