List of usage examples for org.apache.commons.httpclient HttpMethod getStatusCode
public abstract int getStatusCode();
From source file:org.apache.wookie.tests.functional.ProxyTest.java
@Test public void getProtectedSiteWithBasicAuth() throws Exception { HttpClient client = new HttpClient(); List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST);//ww w. j a va 2s . c o m authPrefs.add(AuthPolicy.BASIC); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); // send the basic authentication response even before the server gives an unauthorized response client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials("java", "java")); HttpMethod req; req = new GetMethod(PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + PROTECTED_SITE_URL); client.executeMethod(req); int code = req.getStatusCode(); req.releaseConnection(); assertEquals(200, code); }
From source file:org.apache.wookie.tests.functional.ProxyTest.java
private int send(String url, String method) { try {//w w w. ja va2 s .c o m HttpClient client = new HttpClient(); HttpMethod req; if (method.equals("POST")) { req = new PostMethod(url); } else { req = new GetMethod(url); } client.executeMethod(req); int code = req.getStatusCode(); req.releaseConnection(); return code; } catch (Exception e) { e.printStackTrace(); fail("post failed"); return -1; } }
From source file:org.artifactory.cli.rest.RestClient.java
/** * Validates the expected returned status * * @param uri Target URL// ww w. j av a 2s.c om * @param expectedStatus Expected returned status * @param method The method after execution (holds the returned status) */ private static void checkStatus(String uri, int expectedStatus, HttpMethod method) { int status = method.getStatusCode(); if (status != expectedStatus) { throw new RemoteCommandException("\nUnexpected response status for request: " + uri + "\n" + "Expected status: " + expectedStatus + " (" + HttpStatus.getStatusText(expectedStatus) + ")" + "\n " + "Received status: " + status + " (" + HttpStatus.getStatusText(status) + ") - " + method.getStatusText() + "\n"); } }
From source file:org.bonitasoft.connectors.webdav.exo.common.ExoConnector.java
/** * process response to get statusCode, statusText and response string. * /* www .j a v a 2 s. c o m*/ * @param httpMethod * @param getResponseAsString */ protected void processResponse(final HttpMethod httpMethod, final boolean getResponseAsString) { String statusCode = "-1"; if (httpMethod.getStatusCode() > 0) { statusCode = String.valueOf(httpMethod.getStatusCode()); } final String statusText = httpMethod.getStatusText(); String responseString = ""; if (getResponseAsString) { try { responseString = httpMethod.getResponseBodyAsString(); if (responseString == null) { responseString = ""; } } catch (final IOException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning("IOException while getting responseAsString: " + e.getMessage()); } e.printStackTrace(); } } if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("status CODE: " + statusCode + ", status TEXT: " + statusText + "\n response string: " + responseString); } this.statusCode = statusCode; this.statusText = statusText; this.response = responseString; }
From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java
protected void execute(HttpMethod httpMethod) throws Exception { // (new HttpClient()).executeMethod(httpMethod); HttpClient client = new HttpClient(); if (submissionMap != null) { String sessionid = submissionMap.get(ChibaAdapter.SESSION_ID).toString(); if (sessionid != null) { HttpState state = client.getState(); state.setCookiePolicy(CookiePolicy.COMPATIBILITY); state.addCookie(new Cookie(httpMethod.getURI().getHost(), "JSESSIONID", sessionid, httpMethod.getPath(), null, false)); client.setState(state);//from w w w. j a va2 s . c o m } } client.executeMethod(httpMethod); if (httpMethod.getStatusCode() >= 300) { throw new XFormsException( "HTTP status " + httpMethod.getStatusCode() + ": " + httpMethod.getStatusText()); } this.handleHttpMethod(httpMethod); }
From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java
private HTTPResponse convertResponse(HttpMethod method) { Headers headers = new Headers(); for (Header header : method.getResponseHeaders()) { headers = headers.add(header.getName(), header.getValue()); }//from w ww . ja va 2 s . c o m InputStream stream = null; HTTPResponse response; try { stream = getInputStream(method); StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()), Status.valueOf(method.getStatusCode()), method.getStatusText()); response = getResponseCreator().createResponse(line, headers, stream); } finally { if (stream == null) { method.releaseConnection(); } } return response; }
From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolverTest.java
private HTTPClientResponseResolver createResponseResolver(final HttpMethod httpMethod, final Status status, final Header[] headers) { try {//from www . j av a 2 s .c o m when(httpMethod.getStatusLine()).thenReturn(new org.apache.commons.httpclient.StatusLine( String.format("HTTP/1.1 %s %s\r\n", status.getCode(), status.getName()))); } catch (HttpException e) { throw new RuntimeException(e); } when(httpMethod.getStatusCode()).thenReturn(status.getCode()); when(httpMethod.getResponseHeaders()).thenReturn(headers); return new TestableHTTPClientResponseResolver(httpMethod); }
From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java
protected void doProxy(URI uri, WebInvocation context) throws ProxyingException { HttpServletRequest hreq = context.getHreq(); HttpServletResponse hres = context.getHres(); long startTime = System.currentTimeMillis(); String m = hreq.getMethod();//from w ww. j av a 2 s. c o m Class clazz = (Class) _methods.get(m); if (clazz == null) { throw new IrrecoverableException("unsupported http method: " + m); } HttpMethod hm = null; try { hm = (HttpMethod) clazz.newInstance(); } catch (Exception e) { throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen } String requestURI = getRequestURI(hreq); hm.setPath(requestURI); String queryString = hreq.getQueryString(); if (queryString != null) { hm.setQueryString(queryString); requestURI += queryString; } hm.setFollowRedirects(false); //hm.setURI(new URI(uri)); hm.setStrictMode(false); // check connection header String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ? if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; // TODO ?? } // copy headers boolean xForwardedFor = false; boolean hasContent = false; int contentLength = 0; Enumeration enm = hreq.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! - using javax.servlet ? String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) { try { contentLength = hreq.getIntHeader(hdr); hasContent = contentLength > 0; } catch (NumberFormatException e) { if (_log.isWarnEnabled()) _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e); } } if ("content-type".equals(lhdr)) { hasContent = true; } Enumeration vals = hreq.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { hm.addRequestHeader(hdr, val); // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ? } } } // cookies... // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending. // we have to explicitly use their interface to add the cookies - painful... // DOH! - an org.apache.commons.httpclient.Cookie is NOT a // javax.servlet.http.Cookie - and it looks like the two don't // map onto each other without data loss... HttpState state = new HttpState(); javax.servlet.http.Cookie[] cookies = hreq.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { javax.servlet.http.Cookie c = cookies[i]; String domain = c.getDomain(); if (domain == null) { domain = hreq.getServerName(); // TODO - tmp test // _log.warn("defaulting cookie domain"); } // domain=null; String cpath = c.getPath(); if (cpath == null) { cpath = hreq.getContextPath(); // fix for Jetty // _log.warn("defaulting cookie path"); } //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length())); Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure()); state.addCookie(cookie); //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString()); } } // Proxy headers hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\""); if (!xForwardedFor) hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr()); // Max-Forwards... // a little bit of cache control // String cache_control = hreq.getHeader("Cache-Control"); // if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) // httpMethod.setUseCaches(false); // customize Connection // uc.setDoInput(true); int client2ServerTotal = 0; if (hasContent) { // uc.setDoOutput(true); try { if (hm instanceof EntityEnclosingMethod) ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream()); // TODO - do we need to close response stream at end... ? } catch (IOException e) { throw new IrrecoverableException("could not pss request input across proxy", e); } } try { HttpClient client = new HttpClient(); HostConfiguration hc = new HostConfiguration(); //String host=location.getAddress().getHostAddress(); // inefficient - but stops httpclient from rejecting half our cookies... String host = uri.getHost(); hc.setHost(host, uri.getPort()); client.executeMethod(hc, hm, state); } catch (IOException e) // TODO { _log.warn("problem proxying connection:", e); } InputStream fromServer = null; // handler status codes etc. int code = 502; // String message="Bad Gateway: could not read server response code or message"; code = hm.getStatusCode(); // IOException // message=hm.getStatusText(); // IOException hres.setStatus(code); // hres.setStatus(code, message); - deprecated... try { fromServer = hm.getResponseBodyAsStream(); // IOException } catch (IOException e) { _log.warn("problem acquiring http client output", e); } // clear response defaults. hres.setHeader("Date", null); hres.setHeader("Server", null); // set response headers // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ? // Try this inside Tomcat... Header[] headers = hm.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { String h = headers[i].toExternalForm(); int index = h.indexOf(':'); String key = h.substring(0, index).trim().toLowerCase(); String val = h.substring(index + 1, h.length()).trim(); if (val != null && !_DontProxyHeaders.contains(key)) { hres.addHeader(key, val); // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val); } } hres.addHeader("Via", "1.1 (WADI)"); // copy server->client int server2ClientTotal = 0; if (fromServer != null) { try { OutputStream toClient = hres.getOutputStream();// IOException server2ClientTotal += copy(fromServer, toClient, 8192);// IOException } catch (IOException e) { _log.warn("problem proxying server response back to client", e); } finally { try { fromServer.close(); } catch (IOException e) { // well - we did our best... _log.warn("problem closing server response stream", e); } } } long endTime = System.currentTimeMillis(); long elapsed = endTime - startTime; if (_log.isDebugEnabled()) { _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:" + elapsed + ", uri:" + uri); } }
From source file:org.cryptomator.ui.controllers.WelcomeController.java
private void checkForUpdates() { checkForUpdatesStatus.setText(localization.getString("welcome.checkForUpdates.label.currentlyChecking")); checkForUpdatesIndicator.setVisible(true); asyncTaskService.asyncTaskOf(() -> { final HttpClient client = new HttpClient(); final HttpMethod method = new GetMethod("https://cryptomator.org/downloads/latestVersion.json"); client.getParams().setParameter(HttpClientParams.USER_AGENT, "Cryptomator VersionChecker/" + ApplicationVersion.orElse("SNAPSHOT")); client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client.getParams().setConnectionManagerTimeout(5000); client.executeMethod(method);// w ww . j a v a2s.c o m final InputStream responseBodyStream = method.getResponseBodyAsStream(); if (method.getStatusCode() == HttpStatus.SC_OK && responseBodyStream != null) { final byte[] responseData = IOUtils.toByteArray(responseBodyStream); final ObjectMapper mapper = new ObjectMapper(); final Map<String, String> map = mapper.readValue(responseData, new TypeReference<HashMap<String, String>>() { }); if (map != null) { this.compareVersions(map); } } }).andFinally(() -> { checkForUpdatesStatus.setText(""); checkForUpdatesIndicator.setVisible(false); }).run(); }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests./*w w w . ja v a2 s .c o m*/ * * @return <code>true</code> if login was successful; <code>false</code> otherwise. * @throws IOException if communication with the radio failed, e.g. because the device is not reachable. */ public boolean doLogin() throws IOException { isLoggedIn = false; // reset login flag if (httpClient == null) { httpClient = new HttpClient(); } final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin; logger.trace("opening URL:" + url); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Communication with radio failed: " + method.getStatusLine()); if (method.getStatusCode() == 403) { throw new RuntimeException("Radio does not allow connection, maybe wrong pin?"); } throw new IOException("Communication with radio failed, return code: " + statusCode); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (HttpException he) { logger.debug("Fatal protocol violation: {}", he.toString()); throw he; } catch (IOException ioe) { logger.debug("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } return false; // login not successful }