/** * Retrieves the content under the given URL with username and passwort * authentication. * * @param url * the URL to read * @param username * @param password * @return the read content. * @throws IOException * if an I/O exception occurs. */ private static byte[] getUrlContent(URL url, String username, String password) throws IOException { final HttpClient client = new HttpClient(); // Set credentials: client.getParams().setAuthenticationPreemptive(true); final Credentials credentials = new UsernamePasswordCredentials( username, password); client.getState() .setCredentials( new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), credentials); // Retrieve content: final GetMethod method = new GetMethod(url.toString()); final int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { throw new IOException("Error " + status + " while retrieving " + url); } return method.getResponseBody(); }
@Override public HttpResponse get(URL urlObj, String userName, String password, int timeout) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlObj.toString()); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); client.getParams().setSoTimeout(1000 * timeout); client.getParams().setConnectionManagerTimeout(1000 * timeout); if (userName != null && password != null) { setBasicAuthorization(method, userName, password); } try { int response = client.executeMethod(method); return new HttpResponse(response, method.getResponseBody()); } catch (IOException e) { throw new RuntimeException("Failed to get " + urlObj.toString(), e); } finally { method.releaseConnection(); } }
public void testPreemptiveAuthProxy() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new FeedbackService()); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); if (isUseSSL()) { assertNull(get.getRequestHeader("Proxy-Authorization")); } else { assertNotNull(get.getRequestHeader("Proxy-Authorization")); } } finally { get.releaseConnection(); } }
/** * Tests GET via authenticating proxy + invalid host auth */ public void testGetProxyAuthHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode()); } finally { get.releaseConnection(); } }
public void testRelativeURLHitWithDefaultHost() throws IOException { this.server.setHttpService(new EchoService()); // Set default host this.client.getHostConfiguration().setHost( this.server.getLocalAddress(), this.server.getLocalPort(), Protocol.getProtocol("http")); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); } finally { httpget.releaseConnection(); } }
private static void tryAuthentication(RemoteFileReference wsReference) throws Exception { URL urlToConnect = wsReference.getUrl(); String wsdlUrl = wsReference.getUrlpath(); String username = wsReference.getAuthUser(); String password = wsReference.getAuthPassword(); HttpClient client = new HttpClient(); client.getState().setCredentials( new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()), new UsernamePasswordCredentials(username, password) ); GetMethod get = new GetMethod(wsdlUrl); get.setDoAuthentication( true ); int statuscode = client.executeMethod(get); if (statuscode == HttpStatus.SC_UNAUTHORIZED) { throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!"); } }
/** * Gets remote resource. * * @return the remove resource * * @throws ResourceException thrown if the resource could not be fetched */ protected GetMethod getResource() throws ResourceException { GetMethod getMethod = new GetMethod(resourceUrl); getMethod.addRequestHeader("Connection", "close"); try { httpClient.executeMethod(getMethod); if (getMethod.getStatusCode() != HttpStatus.SC_OK) { throw new ResourceException("Unable to retrieve resource URL " + resourceUrl + ", received HTTP status code " + getMethod.getStatusCode()); } return getMethod; } catch (IOException e) { throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); } }
/** * Builds the HTTP GET method used to fetch the metadata. The returned method advertises support for GZIP and * deflate compression, enables conditional GETs if the cached metadata came with either an ETag or Last-Modified * information, and sets up basic authentication if such is configured. * * @return the constructed GET method */ protected GetMethod buildGetMethod() { GetMethod getMethod = new GetMethod(getMetadataURI()); getMethod.addRequestHeader("Connection", "close"); getMethod.setRequestHeader("Accept-Encoding", "gzip,deflate"); if (cachedMetadataETag != null) { getMethod.setRequestHeader("If-None-Match", cachedMetadataETag); } if (cachedMetadataLastModified != null) { getMethod.setRequestHeader("If-Modified-Since", cachedMetadataLastModified); } if (httpClient.getState().getCredentials(authScope) != null) { log.debug("Using BASIC authentication when retrieving metadata from '{}", metadataURI); getMethod.setDoAuthentication(true); } return getMethod; }
public void testBasicRedirect301() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_MOVED_PERMANENTLY)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } }
public void testPreemptiveAuthProxyWithCrossSiteRedirect() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new BasicRedirectService( "http://127.0.0.1:" + this.server.getLocalPort())); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/redirect/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } }
/** * Tests response with a Trasfer-Encoding and Content-Length */ public void testHttpMethodBaseTEandCL() throws Exception { this.server.setHttpService(new SimpleChunkedService()); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("1234567890123", httpget.getResponseBodyAsString()); assertTrue(this.client.getHttpConnectionManager() instanceof SimpleHttpConnectionManager); HttpConnection conn = this.client.getHttpConnectionManager(). getConnection(this.client.getHostConfiguration()); assertNotNull(conn); conn.assertNotOpen(); } finally { httpget.releaseConnection(); } }
public void testDefaults() throws IOException { this.server.setHttpService(new SimpleService()); this.client.getParams().setParameter(HttpMethodParams.USER_AGENT, "test"); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost( this.server.getLocalAddress(), this.server.getLocalPort(), Protocol.getProtocol("http")); GetMethod httpget = new GetMethod("/miss/"); try { this.client.executeMethod(hostconfig, httpget); } finally { httpget.releaseConnection(); } assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("test", httpget.getRequestHeader("User-Agent").getValue()); assertEquals("test", httpget.getParams(). getParameter(HttpMethodParams.USER_AGENT)); assertEquals("test", hostconfig.getParams(). getParameter(HttpMethodParams.USER_AGENT)); assertEquals("test", client.getParams(). getParameter(HttpMethodParams.USER_AGENT)); }
public void testCreateNodeMultipart() throws IOException { final String url = HTTP_BASE_URL + "/CreateNodeTest_2_" + System.currentTimeMillis(); // add some properties to the node final Map<String,String> props = new HashMap<String,String>(); props.put("name1","value1B"); props.put("name2","value2B"); // POST and get URL of created node String urlOfNewNode = null; try { urlOfNewNode = testClient.createNode(url, props, null, true); } catch(IOException ioe) { fail("createNode failed: " + ioe); } // check node contents (not all renderings - those are tested above) final GetMethod get = new GetMethod(urlOfNewNode + DEFAULT_EXT); final int status = httpClient.executeMethod(get); assertEquals(urlOfNewNode + " must be accessible after createNode",200,status); final String responseBodyStr = get.getResponseBodyAsString(); assertTrue(responseBodyStr.contains("value1B")); assertTrue(responseBodyStr.contains("value2B")); }
/** * Tests empty body response */ public void testEmptyBodyAsString() throws Exception { this.server.setHttpService(new EmptyResponseService()); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); String response = httpget.getResponseBodyAsString(); assertNull(response); this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); response = httpget.getResponseBodyAsString(1); assertNull(response); } finally { httpget.releaseConnection(); } }
/** * Test SLING-1847 * @throws Exception */ @Test public void testRedirectToResourceAfterLogout() throws Exception { //login List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_username", "admin")); params.add(new NameValuePair("j_password", "admin")); H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY, params, null); //...and then...logout with a resource redirect String locationAfterLogout = HttpTest.SERVLET_CONTEXT + "/system/sling/info.sessionInfo.json"; final GetMethod get = new GetMethod(HttpTest.HTTP_BASE_URL + "/system/sling/logout"); NameValuePair [] logoutParams = new NameValuePair[1]; logoutParams[0] = new NameValuePair("resource", locationAfterLogout); get.setQueryString(logoutParams); get.setFollowRedirects(false); final int status = H.getHttpClient().executeMethod(get); assertEquals("Expected redirect", HttpServletResponse.SC_MOVED_TEMPORARILY, status); Header location = get.getResponseHeader("Location"); assertEquals(HttpTest.HTTP_BASE_URL + locationAfterLogout, location.getValue()); }
/** test vanity path with 301 redirect */ public void test301Redirect() throws IOException { // create a node with a vanity path Map<String, String> props = new HashMap<String, String>(); props.put("jcr:mixinTypes", "sling:VanityPath"); props.put("sling:vanityPath", vanityPath); props.put("sling:redirect", "true"); props.put("sling:redirectStatus", "301"); String createdNodeUrl = testClient.createNode(postUrl, props); waitForMapReload(); // get the created node without following redirects GetMethod get = new GetMethod(vanityUrl); get.setFollowRedirects(false); int status = httpClient.executeMethod(get); // expect permanent redirect ... assertEquals(301, status); // ... to the created node String location = get.getResponseHeader("Location").getValue(); assertNotNull(location); assertEquals(removeHttpBase(createdNodeUrl) + ".html", location); }
@Test public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception { // assume http and webdav are on the same host + port URL url = new URL(HttpTest.HTTP_BASE_URL); Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage"); H.getHttpClient().getState() .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds); final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1"; HttpMethod get = new GetMethod(requestUrl); get.setRequestHeader("Referer", requestUrl); get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test"); int status = H.getHttpClient().executeMethod(get); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status); }
public void testChunkedConsitance() throws IOException { String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream out = new ChunkedOutputStream(buffer); out.write(EncodingUtil.getBytes(input, CONTENT_CHARSET)); out.close(); buffer.close(); InputStream in = new ChunkedInputStream(new ByteArrayInputStream(buffer.toByteArray()), new GetMethod()); byte[] d = new byte[10]; ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } String output = EncodingUtil.getString(result.toByteArray(), CONTENT_CHARSET); assertEquals(input, output); }
@Test @Retry public void testInfiniteLoopDetection() throws IOException { // Node C has a property that causes an infinite include loop, // Sling must indicate the problem in its response final GetMethod get = new GetMethod(nodeUrlC + ".html"); H.getHttpClient().executeMethod(get); final String content = get.getResponseBodyAsString(); assertTrue( "Response contains infinite loop error message", content.contains("org.apache.sling.api.request.RecursionTooDeepException")); // TODO: SLING-515, status is 500 when running the tests as part of the maven build // but 200 if running tests against a separate instance started with mvn jetty:run // final int status = get.getStatusCode(); // assertEquals("Status is 500 for infinite loop",HttpServletResponse.SC_INTERNAL_SERVER_ERROR, status); }
private void checkUploadedFileState(String urlOfFileNode) throws IOException, HttpException { final GetMethod get = new GetMethod(urlOfFileNode); final int status = httpClient.executeMethod(get); assertEquals(urlOfFileNode + " must be accessible after createNode",200,status); /* We should check the data, but nt:resources are not handled yet // compare data with local file (just length) final byte[] data = get.getResponseBody(); assertEquals("size of file must be same", localFile.length(), data.length); */ String data = get.getResponseBodyAsString(); assertTrue("checking for content", data.contains("http://www.apache.org/licenses/LICENSE-2.0")); // download structure String json = getContent(urlOfFileNode + ".json", CONTENT_TYPE_JSON); // just check for some strings assertTrue("checking primary type", json.contains("\"jcr:primaryType\":\"nt:file\"")); String content_json = getContent(urlOfFileNode + "/jcr:content.json", CONTENT_TYPE_JSON); // just check for some strings assertTrue("checking primary type", content_json.contains("\"jcr:primaryType\":\"nt:resource\"")); assertTrue("checking mime type", content_json.contains("\"jcr:mimeType\":\"text/plain\"")); }
public void testCookieVersionSupportHeader2() throws IOException { this.server.setHttpService(new CookieVer1Service()); this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); GetMethod httpget1 = new GetMethod("/test/"); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } GetMethod httpget2 = new GetMethod("/test/"); try { this.client.executeMethod(httpget2); } finally { httpget2.releaseConnection(); } Header cookiesupport = httpget2.getRequestHeader("Cookie2"); assertNull(cookiesupport); }
/** * Tests GET via non-authenticating proxy + invalid host auth */ public void testGetHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.server.setRequestHandler(handlerchain); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode()); } finally { get.releaseConnection(); } }
/** * 同步客户端3.X版本 * * @return */ @GET @Path("httpclient3test") public String httpClient3Test() { HttpClient httpClient = new HttpClient(); HttpMethod method = new GetMethod("https://www.baidu.com/"); try { httpClient.executeMethod(method); System.out.println(method.getURI()); System.out.println(method.getStatusLine()); System.out.println(method.getName()); System.out.println(method.getResponseHeader("Server").getValue()); System.out.println(method.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); } return "httpClient3 test success"; }
public void testBasicRedirect304() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_NOT_MODIFIED)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_NOT_MODIFIED, httpget.getStatusCode()); assertEquals("/oldlocation/", httpget.getPath()); assertEquals(new URI("/oldlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } }
public HttpResponse get(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId, final String relationCollectionName, final Object relationshipEntityId, Map<String, String> params, Map<String, String> headers) throws IOException { if (headers == null) { headers = Collections.emptyMap(); } RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); String url = endpoint.getUrl(); GetMethod req = new GetMethod(url); for (Entry<String, String> header : headers.entrySet()) { req.addRequestHeader(header.getKey(), header.getValue()); } return submitRequest(req, rq); }
/** * Direct unit test for host versification in SSL. * The test has been proposed as a patch in <a href="https://issues.apache.org/jira/browse/HTTPCLIENT-1265">HTTPCLIENT-1265</a> */ @Issue("SECURITY-555") public void testHostNameValidation() { HttpClient client = new HttpClient(); if (PROXY_HOST != null) { if (PROXY_USER != null) { HttpState state = client.getState(); state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials( PROXY_USER, PROXY_PASS)); } client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT)); } GetMethod method = new GetMethod(_urlWithIp); try { client.executeMethod(method); fail("Invalid hostname not detected"); } catch (SSLException e) { assertTrue("Connection with a invalid server certificate rejected", true); } catch (Throwable t) { t.printStackTrace(); fail("Unexpected exception" + t.getMessage()); } }
/** * Tests ability to use HTTP/1.0 to execute CONNECT method and HTTP/1.1 to * execute methods once the tunnel is established. */ public void testTunnellingParamsHostHTTP10AndMethodHTTP11() throws IOException { this.proxy.addHandler(new HttpVersionHandler()); this.server.setHttpService(new FeedbackService()); this.client.getHostConfiguration().getParams().setParameter( HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); GetMethod httpget = new GetMethod("/test/"); httpget.getParams().setVersion(HttpVersion.HTTP_1_1); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); assertEquals(HttpVersion.HTTP_1_1, httpget.getEffectiveVersion()); } finally { httpget.releaseConnection(); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ String item = request.getParameter("item"); //in HttpClient 4.x, there is no GetMethod anymore. Instead there is HttpGet HttpGet httpget = new HttpGet("http://host.com?param=" + URLEncoder.encode(item)); //OK HttpGet httpget2 = new HttpGet("http://host.com?param=" + item); //BAD GetMethod get = new GetMethod("http://host.com?param=" + item); //BAD get.setQueryString("item=" + item); //BAD //get.execute(); }catch(Exception e){ System.out.println(e); } }
/** * Test {@link HttpMethod#setRequestHeader}. */ public void testOverwriteRequestHeader() throws Exception { this.server.setHttpService(new HeaderDumpService()); GetMethod method = new GetMethod("/"); method.setRequestHeader(new Header("xxx-a-header","one")); method.setRequestHeader("XXX-A-HEADER","two"); try { this.client.executeMethod(method); String s = method.getResponseBodyAsString(); assertTrue(s.indexOf("name=\"xxx-a-header\";value=\"two\"") >= 0); } finally { method.releaseConnection(); } }
private static GetMethod getHttpGet(String url, String cookie, String userAgent) { GetMethod httpGet = new GetMethod(url); httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET); httpGet.setRequestHeader("Connection", "Keep-Alive"); httpGet.setRequestHeader("User-Agent", userAgent); return httpGet; }
public void testUrlGetMethod() { GetMethod method = new GetMethod("http://www.fubar.com/"); try { assertEquals( "Get URL", "http://www.fubar.com/", method.getURI().toString() ); } catch ( URIException e ) { fail( "trouble getting URI: " + e ); } assertEquals("Get Path", "/", method.getPath()); assertEquals("Get query string", null, method.getQueryString()); }
public static final String httpClientPost(String url) { String result = ""; HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(url); try { client.executeMethod(getMethod); result = getMethod.getResponseBodyAsString(); } catch (Exception e) { logger.error("", e); } finally { getMethod.releaseConnection(); } return result; }
public void testCircularRedirect() throws IOException { this.server.setHttpService(new CircularRedirectService()); GetMethod httpget = new GetMethod("/circular-oldlocation/"); try { this.client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false); this.client.executeMethod(httpget); fail("CircularRedirectException exception should have been thrown"); } catch (CircularRedirectException expected) { } finally { httpget.releaseConnection(); } }
public static final String httpClientPost(String url) { String result = ""; HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(url); try { client.executeMethod(getMethod); result = getMethod.getResponseBodyAsString(); } catch (Exception e) { logger.error(e); } finally { getMethod.releaseConnection(); } return result; }
public void testAbortedMethodExecute() throws IOException { final GetMethod httpget = new GetMethod("/test/"); try { httpget.abort(); try { this.client.executeMethod(httpget); fail("IllegalStateException must have been thrown"); } catch (IllegalStateException e) { } } finally { httpget.releaseConnection(); } assertTrue(httpget.isAborted()); }
/** * Send a GET request * @param c the cluster definition * @param path the path or URI * @param headers the HTTP headers to include in the request * @return a Response object with response detail * @throws IOException */ public Response get(Cluster c, String path, Header[] headers) throws IOException { GetMethod method = new GetMethod(); try { int code = execute(c, method, headers, path); headers = method.getResponseHeaders(); byte[] body = method.getResponseBody(); InputStream in = method.getResponseBodyAsStream(); return new Response(code, headers, body, in); } finally { method.releaseConnection(); } }
/** * Checks all the servers marked as being online * if they still are online. */ private synchronized void checkOnlineServers() { Iterator itr; itr = online.listIterator(); while (itr.hasNext()) { Server server = (Server) itr.next(); String url = getServerURL(server); GetMethod get = new GetMethod(url); get.setFollowRedirects(false); try { httpClient.executeMethod(get); if (!okServerResponse(get.getStatusCode())) { offline.add(server); itr.remove(); log.debug("Server going OFFLINE! " + getServerURL(server)); listener.serverOffline(server); } } catch (Exception e) { offline.add(server); itr.remove(); log.debug("Server going OFFLINE! " + getServerURL(server)); listener.serverOffline(server); } finally { get.releaseConnection(); } } }
public void testIgnoreCookies() throws Exception { this.server.setHttpService(new BasicAuthService()); GetMethod httpget = new GetMethod("/"); httpget.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertEquals("Cookie parsing should have been disabled", 0, this.client.getState().getCookies().length); }
public void testInvalidContentLength2() throws Exception { this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Content-Length", "stuff")); response.addHeader(new Header("Content-Length", "5")); response.setBodyString("12345"); return true; } }); GetMethod method = new GetMethod("/"); client.executeMethod(method); assertEquals(5, method.getResponseContentLength()); }