HttpConnection conn = Http.POST(url, mimeType); conn.requestProperties.put("accept", accept); conn.setRequestBody(payload); conn.responseInterceptors.remove(this); HttpConnection connection = conn.execute(); int responseCode = connection.getConnection().getResponseCode(); } else { String error = Utils.collectAndCloseStream(connection.getConnection() .getErrorStream());
inputStream = connection.execute().responseAsInputStream(); } catch (IOException ioe) { cause = ioe; responseCode = connection.getConnection().getResponseCode(); responseMessage = connection.getConnection().getResponseMessage(); } catch (IOException ioe) { responseMessage = "Error retrieving server response message"; errorStream = connection.getConnection().getErrorStream();
private HttpConnection postAndAssertNothingReadBeforeSettingBodyGenerator(CouchConfig config) throws Exception { HttpConnection conn = new HttpConnection("POST", config.getRootUri().toURL(), "application/json"); // nothing read from stream Assert.assertEquals(bis.available(), data.getBytes().length); conn.setRequestBody(new HttpConnection.InputStreamGenerator() { @Override public InputStream getInputStream() { return bis; } }); // This test invokes HttpConnection directly rather than via the CouchClient, so we need to // force the addition of some default interceptors conn.requestInterceptors.addAll(CouchClient.DEFAULT_REQUEST_INTERCEPTORS); return conn; }
@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; } } }
/** * <p> * Return response body data from server as a byte array. * </p> * <p> * <b>Important:</b> you must call <code>execute()</code> before calling this method. * </p> * * @return Byte array of response body data from server, if any * @throws IOException if there was a problem reading data from the server */ public byte[] responseAsBytes() throws IOException { InputStream is = responseAsInputStream(); try { return IOUtils.toByteArray(is); } finally { Utils.close(is); disconnect(); } }
+ ":" + CloudantClientHelper.COUCH_PASSWORD); HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json"); conn.requestInterceptors.add(interceptor); conn.setRequestBody(bis); HttpConnection responseConn = conn.execute(); assertEquals(2, responseConn.getConnection().getResponseCode() / 100); InputStream is = responseConn.responseAsInputStream(); try { JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class);
/** * Set the InputStream of request body data to be sent to the server. * * @param input InputStream of request body data to be sent to the server * @return an {@link HttpConnection} for method chaining * @deprecated Use {@link #setRequestBody(InputStreamGenerator)} */ public HttpConnection setRequestBody(final InputStream input) { // -1 signals inputLength unknown return setRequestBody(input, -1); }
@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"); }
@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { context.connection.getConnection().setRequestProperty("User-Agent", userAgent); return context; }
connection = Http.POST(uri, "application/json"); if (jsonObject.toString().length() != 0) { connection.setRequestBody(jsonObject.toString()); responseStream = connection.responseAsInputStream(); List<Response> bulkResponses = getResponseList(responseStream, getGson(), DeserializationTypes.LC_RESPONSES); for(Response response : bulkResponses) { response.setStatusCode(connection.getConnection().getResponseCode());
@Override public boolean call(HttpConnection connection) throws IOException { iamTokenResponse.set(connection.responseAsString()); return true; } }
connection = connection.execute(); } catch (HttpConnectionInterceptorException e) { CouchDbException exception = new CouchDbException(connection.getConnection() .getResponseMessage(), connection.getConnection().getResponseCode()); if (e.deserialize) { try { int code = connection.getConnection().getResponseCode(); String response = connection.getConnection().getResponseMessage(); break; es = connection.getConnection().getErrorStream();
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();
@Test public void httpMethodFilterLogging() throws Exception { setAndAssertLogProperty(methodFilterPropName, "GET"); logger = setupLogger(HttpConnection.class, Level.FINE); // Make a GET request client.executeRequest(Http.GET(client.getBaseUri())).responseAsString(); // Check there were two log messages one for request and one for response assertEquals(2, handler.logEntries.size(), "There should be 2 log messages"); // Check the messages were the ones we expected assertHttpMessage("GET .* request", 0); assertHttpMessage("GET .* response 200 OK", 1); // Store the current log size int logsize = handler.logEntries.size(); // Make a PUT request to a different URL and check that nothing else was logged client.executeRequest(Http.PUT(client.getBaseUri(), "text/plain").setRequestBody("")) .responseAsString(); assertEquals(logsize, handler.logEntries.size(), "There should have been no more log " + "entries"); }
@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(); }
/** * Closes a REST response. */ private static void closeResponse(HttpConnection response) throws Exception { InputStream responseStream = response.responseAsInputStream(); IOUtils.closeQuietly(responseStream); }
@TestTemplate public void testReadBeforeExecute() 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); try { String response = conn.responseAsString(); fail("IOException not thrown as expected instead had response " + response); } catch (IOException ioe) { ; // "Attempted to read response from server before calling execute()" } // stream was not read because execute() was not called assertEquals(data.getBytes().length, bis.available()); }
public static boolean isCouchDBV2(URI uri) throws URISyntaxException, IOException { URI root = new URI(uri.getScheme() + "://" + uri.getAuthority()); HttpConnection connection = Http.GET(root); String response = connection.execute().responseAsString(); return response.contains("\"version\":\"2."); }
d.responseAsString(); assertTrue(d.getConnection().getResponseCode() / 100 == 2, "The first request should " + "succeed"); String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString(); fail("A CouchDbException should be thrown, but had response " + response); } catch (CouchDbException e) {
public static List<String> getRemoteRevisionIDs(URI uri, CouchConfig config) throws Exception{ HttpConnection connection = Http.GET(uri); connection.requestInterceptors.addAll(config.getRequestInterceptors()); connection.responseInterceptors.addAll(config.getResponseInterceptors()); InputStream in = connection.execute().responseAsInputStream(); Map<String, Object> m = JSONUtils.fromJson(new InputStreamReader(in)); List<Object> revsInfo = (List<Object>)m.get("_revs_info"); List<String> revisions = new ArrayList<String>(revsInfo.size()); for(Object rev : revsInfo){ revisions.add(((Map<String, String>)rev).get("rev")); } return revisions; }