@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { context.connection.getConnection().setRequestProperty("User-Agent", userAgent); return context; }
@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); return context; }
@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); if (connection instanceof HttpsURLConnection) { HttpsURLConnection secureConnection = (HttpsURLConnection) connection; if (sslSocketFactory != null) { secureConnection.setSSLSocketFactory(sslSocketFactory); } if (hostnameVerifier != null) { secureConnection.setHostnameVerifier(hostnameVerifier); } } return context; }
@Override public boolean call(HttpConnection connection) throws IOException { if (sessionHasStarted(connection.responseAsInputStream())) { return storeCookiesFromResponse(connection.getConnection()); } else { // If the session did not start, consume the error stream to avoid // leaking connections. Utils.consumeAndCloseStream(connection.getConnection().getErrorStream ()); return false; } } }
@Override public HttpConnectionInterceptorContext interceptRequest (HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); connection.setRequestProperty(headerKey, headerValue); return context; } };
@Override public HttpConnectionInterceptorContext interceptResponse (HttpConnectionInterceptorContext context) { revisionRef.set(context.connection.getConnection().getHeaderField("ETag")); return context; } });
public String getDocumentRev(String id) { URI doc = this.uriHelper.documentUri(id); HttpConnection head = Http.HEAD(doc); executeWithRetry(head, new NoOpInputStreamProcessor()); String rev = head.getConnection().getHeaderField("ETag"); // Remove enclosing "" before returning return rev.substring(1, rev.length() - 1); }
@Override public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { // Check if this interceptor is valid before attempting any kind of renewal try { if (shouldAttemptCookieRequest.get()) { HttpURLConnection connection = context.connection.getConnection(); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { boolean success = requestCookie(context); if (success) { context.replayRequest = true; // Consume the error stream to avoid leaking connections Utils.consumeAndCloseStream(connection.getErrorStream()); logger.log(Level.FINEST, "Consumed error response"); } else { context.replayRequest = false; // Don't replay shouldAttemptCookieRequest.set(false); // Set the flag to stop trying } } else { // Store any cookies provided on the response storeCookiesFromResponse(connection); } } } catch (IOException e) { logger.log(Level.SEVERE, "Error reading response code or body from request", e); } return context; }
@Override public HttpConnectionInterceptorContext interceptResponse (HttpConnectionInterceptorContext context) { try { if (444 == context.connection.getConnection().getResponseCode()) { context.replayRequest = true; // Close the error stream InputStream errors = context.connection.getConnection().getErrorStream(); if (errors != null) { IOUtils.closeQuietly(errors); } } } catch (IOException e) { e.printStackTrace(); fail("IOException getting response code in test interceptor"); } return context; } }).build().executeRequest(request);
@Override public HttpConnectionInterceptorContext interceptResponse (HttpConnectionInterceptorContext context) { // At least do something with the connection, otherwise we risk breaking it try { context.connection.getConnection().getResponseCode(); } catch (IOException e) { fail("IOException getting response code"); } // Set to always replay context.replayRequest = true; return context; } })
/** * Executes a HTTP request and parses the JSON response into a Response instance. * * @param connection The HTTP request to execute. * @return Response object of the deserialized JSON response */ public Response executeToResponse(HttpConnection connection) { InputStream is = null; try { is = this.executeToInputStream(connection); Response response = getResponse(is, Response.class, getGson()); response.setStatusCode(connection.getConnection().getResponseCode()); response.setReason(connection.getConnection().getResponseMessage()); return response; } catch (IOException e) { throw new CouchDbException("Error retrieving response code or message.", e); } finally { close(is); } }
@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { Assert.assertEquals(context.connection.getConnection().getRequestProperty("x-good-header"), "test"); return context; } });
/** * Removes a design document from the database. * * @param id the document id (optionally prefixed with "_design/") * @return {@link DesignDocument} */ public Response remove(String id) { assertNotEmpty(id, "id"); id = ensureDesignPrefix(id); String revision = null; // Get the revision ID from ETag, removing leading and trailing " revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri() ).documentUri(id))).getConnection().getHeaderField("ETag"); if (revision != null) { revision = revision.substring(1, revision.length() - 1); return db.remove(id, revision); } else { throw new CouchDbException("No ETag header found for design document with id " + id); } }
public static int executeHttpPostRequest(URI uri, String payload, CouchConfig config) { HttpConnection connection = Http.POST(uri, "application/json"); connection.requestInterceptors.addAll(config.getRequestInterceptors()); connection.responseInterceptors.addAll(config.getResponseInterceptors()); try { connection.setRequestBody(payload); connection.execute(); } catch (Exception e) { ; // ignore exception } try { return connection.getConnection().getResponseCode(); } catch (Exception e) { System.out.println("*** got ex "+e); return 0; } }
@TestTemplate public void testWriteToServerOk() throws Exception { HttpConnection conn = new HttpConnection("POST", new URL(dbResource.getDbURIWithUserInfo()), "application/json"); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); // nothing read from stream assertEquals(data.getBytes().length, bis.available()); conn.setRequestBody(bis); HttpConnection response = conn.execute(); // Consume response stream String responseStr = response.responseAsString(); String okPattern = ".*\"ok\"\\s*:\\s*true.*"; assertTrue(Pattern.compile(okPattern, Pattern.DOTALL).matcher(responseStr).matches(), "There should be an ok response: " + "" + responseStr); // stream was read to end assertEquals(0, bis.available()); assertEquals(2, response.getConnection().getResponseCode () / 100, "Should be a 2XX response code"); }
Assert.assertEquals(2, conn.getConnection().getResponseCode() / 100); Map<String, Object> jsonRes = JSONUtils.fromJson(new InputStreamReader(conn.getConnection() .getInputStream()));
assertEquals(2, responseConn.getConnection().getResponseCode() / 100);
@TestTemplate @RequiresCloudant public void testCookieAuthWithoutRetry() throws IOException { CookieInterceptor interceptor = new CookieInterceptor(CloudantClientHelper.COUCH_USERNAME, CloudantClientHelper.COUCH_PASSWORD, clientResource.get().getBaseUri().toString()); HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json"); conn.responseInterceptors.add(interceptor); conn.requestInterceptors.add(interceptor); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); // nothing read from stream assertEquals(data.getBytes().length, bis.available()); conn.setRequestBody(bis); HttpConnection responseConn = conn.execute(); // stream was read to end assertEquals(0, bis.available()); assertEquals(2, responseConn.getConnection().getResponseCode() / 100); //check the json Gson gson = new Gson(); InputStream is = responseConn.responseAsInputStream(); try { JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class); assertTrue(response.has("ok")); assertTrue(response.get("ok").getAsBoolean()); assertTrue(response.has("id")); assertTrue(response.has("rev")); } finally { is.close(); } }
conn.setRequestBody("{\"foo\":\"" + TESTSTRING_ESCAPED + "\"}"); clientResource.get().executeRequest(conn); assertEquals(2, conn.getConnection().getResponseCode() / 100); closeResponse(conn); conn.requestProperties.put("Accept", "application/json"); clientResource.get().executeRequest(conn); assertEquals(200, conn.getConnection().getResponseCode()); String result = getPlainTextEntityAsString(conn, uri); assertEquals(EXPECTED_JSON, result); conn.requestProperties.put("Accept", "application/json"); clientResource.get().executeRequest(conn); assertEquals(200, conn.getConnection().getResponseCode()); JsonObject result = getJSONEntityAsJsonObject(conn, uri); String value = result.get("foo").getAsString();
@TestTemplate public void testCookieRenewOnPost() throws Exception { mockWebServer.enqueue(MockWebServerResources.OK_COOKIE); mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody ("{\"error\":\"credentials_expired\", \"reason\":\"Session expired\"}\r\n")); mockWebServer.enqueue(MockWebServerResources.OK_COOKIE); mockWebServer.enqueue(new MockResponse()); CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer) .username("a") .password("b") .build(); HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json"); request.setRequestBody("{\"some\": \"json\"}"); HttpConnection response = c.executeRequest(request); String responseStr = response.responseAsString(); assertTrue(responseStr.isEmpty(), "There should be no response body on the mock response"); response.getConnection().getResponseCode(); }