List of usage examples for org.apache.commons.httpclient HttpMethod getStatusCode
public abstract int getStatusCode();
From source file:org.mozilla.zest.impl.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method; URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break;//from ww w .j av a 2 s .com case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after Header contentType = method.getRequestHeader("Content-Type"); RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); if (contentType != null) { method.setRequestHeader(contentType); } } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders()); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) { // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests method = new GetMethod(method.getResponseHeader("Location").getValue()); // Just in case there are multiple redirects method.setFollowRedirects(req.isFollowRedirects()); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders()); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } } return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }
From source file:org.mule.ibeans.module.http.HttpClientMessageRequester2.java
/** * Make a specific request to the underlying transport * * @param timeout the maximum time the operation should block before returning. * The call should return immediately if there is data available. If * no data becomes available before the timeout elapses, null will be * returned// w w w . ja v a 2s . co m * @return the result of the request wrapped in a MuleMessage object. Null will be * returned if no data was avaialable * @throws Exception if the call to the underlying protocal cuases an exception */ protected MuleMessage doRequest(long timeout) throws Exception { HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress()); if (endpoint.getProperties().containsKey(HttpConstants.HEADER_AUTHORIZATION)) { httpMethod.setDoAuthentication(true); client.getParams().setAuthenticationPreemptive(true); httpMethod.setRequestHeader(HttpConstants.HEADER_AUTHORIZATION, (String) endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION)); } boolean releaseConn = false; try { HttpClient client = new HttpClient(); if (etag != null && checkEtag) { httpMethod.setRequestHeader(HttpConstants.HEADER_IF_NONE_MATCH, etag); } client.executeMethod(httpMethod); if (httpMethod.getStatusCode() < 400) { MuleMessage message = new HttpMuleMessageFactory(connector.getMuleContext()).create(httpMethod, null /* encoding */); etag = message.getInboundProperty(HttpConstants.HEADER_ETAG, null); if (httpMethod.getStatusCode() == HttpStatus.SC_OK || (httpMethod.getStatusCode() != HttpStatus.SC_NOT_MODIFIED || !checkEtag)) { if (StringUtils.EMPTY.equals(message.getPayload())) { releaseConn = true; } return message; } else { //Not modified, we should really cache the whole message and return it return new DefaultMuleMessage(NullPayload.getInstance(), getConnector().getMuleContext()); } } else { releaseConn = true; throw new ReceiveException( HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint, timeout); } } catch (ReceiveException e) { releaseConn = true; throw e; } catch (Exception e) { releaseConn = true; throw new ReceiveException(endpoint, timeout, e); } finally { if (releaseConn) { httpMethod.releaseConnection(); } } }
From source file:org.mule.transport.as2.As2MessageDispatcher.java
@Override protected void doDispatch(MuleEvent event) throws Exception { logger.debug("DBG: inside " + getClass() + ".doDispatch()"); HttpMethod httpMethod = getMethod(event); as2Connector.setupClientAuthorizationLocal(event, httpMethod, client, endpoint); try {//from w ww .j a v a2 s . c o m execute(event, httpMethod); if (returnException(event, httpMethod)) { logger.error(httpMethod.getResponseBodyAsString()); Exception cause = new Exception(String.format("Http call returned a status of: %1d %1s", httpMethod.getStatusCode(), httpMethod.getStatusText())); throw new DispatchException(event, getEndpoint(), cause); } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) { if (logger.isInfoEnabled()) { logger.info("Received a redirect response code: " + httpMethod.getStatusCode() + " " + httpMethod.getStatusText()); } } else { logger.debug("DBG: response Body is: " + httpMethod.getResponseBodyAsString()); /* Check the incoming synch MDN */ MimeMultipart mdn = MDNBuilder.createMDNFromResponse(httpMethod.getResponseBodyAsStream(), "multipart/report"); if (MDNBuilder.identifyMdnType(mdn) != MdnType.PROCESSED) { throw new Exception("MDN is not of type PROCESSED"); } } } finally { httpMethod.releaseConnection(); } }
From source file:org.mule.transport.as2.As2MuleMessageFactory.java
@Override protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception { String method;//w w w . j ava2 s . c o m HttpVersion httpVersion; String uri; String statusCode = null; Map<String, Object> headers; Map<String, Object> httpHeaders = new HashMap<String, Object>(); Map<String, Object> queryParameters = new HashMap<String, Object>(); if (transportMessage instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) transportMessage; method = httpRequest.getRequestLine().getMethod(); httpVersion = httpRequest.getRequestLine().getHttpVersion(); uri = httpRequest.getRequestLine().getUri(); headers = convertHeadersToMap(httpRequest.getHeaders(), uri); convertMultiPartHeaders(headers); } else if (transportMessage instanceof HttpMethod) { HttpMethod httpMethod = (HttpMethod) transportMessage; method = httpMethod.getName(); httpVersion = HttpVersion.parse(httpMethod.getStatusLine().getHttpVersion()); uri = httpMethod.getURI().toString(); statusCode = String.valueOf(httpMethod.getStatusCode()); headers = convertHeadersToMap(httpMethod.getResponseHeaders(), uri); } else { // This should never happen because of the supported type checking in our superclass throw new MessageTypeNotSupportedException(transportMessage, getClass()); } rewriteConnectionAndKeepAliveHeaders(headers); headers = processIncomingHeaders(headers); httpHeaders.put(HttpConnector.HTTP_HEADERS, new HashMap<String, Object>(headers)); String encoding = getEncoding(headers); queryParameters.put(HttpConnector.HTTP_QUERY_PARAMS, processQueryParams(uri, encoding)); //Make any URI params available ans inbound message headers addUriParamsAsHeaders(headers, uri); headers.put(HttpConnector.HTTP_METHOD_PROPERTY, method); headers.put(HttpConnector.HTTP_REQUEST_PROPERTY, uri); headers.put(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion.toString()); if (enableCookies) { headers.put(HttpConnector.HTTP_COOKIE_SPEC_PROPERTY, cookieSpec); } if (statusCode != null) { headers.put(HttpConnector.HTTP_STATUS_PROPERTY, statusCode); } message.addInboundProperties(headers); message.addInboundProperties(httpHeaders); message.addInboundProperties(queryParameters); // The encoding is stored as message property. To avoid overriding it from the message // properties, it must be initialized last initEncoding(message, encoding); }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
@Override protected void doDispatch(MuleEvent event) throws Exception { HttpMethod httpMethod = getMethod(event); httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint); try {// ww w. j a v a2s . co m execute(event, httpMethod); if (returnException(event, httpMethod)) { logger.error(httpMethod.getResponseBodyAsString()); Exception cause = new Exception(String.format("Http call returned a status of: %1d %1s", httpMethod.getStatusCode(), httpMethod.getStatusText())); throw new DispatchException(event, getEndpoint(), cause); } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) { if (logger.isInfoEnabled()) { logger.info("Received a redirect response code: " + httpMethod.getStatusCode() + " " + httpMethod.getStatusText()); } } } finally { httpMethod.releaseConnection(); } }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
@Override protected MuleMessage doSend(MuleEvent event) throws Exception { HttpMethod httpMethod = getMethod(event); httpConnector.setupClientAuthorization(event, httpMethod, client, endpoint); httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new MuleHttpMethodRetryHandler()); boolean releaseConn = false; try {//from ww w .j a va 2 s. c o m httpMethod = execute(event, httpMethod); DefaultExceptionPayload ep = null; if (returnException(event, httpMethod)) { ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), new HttpResponseException(httpMethod.getStatusText(), httpMethod.getStatusCode()))); } else if (httpMethod.getStatusCode() >= REDIRECT_STATUS_CODE_RANGE_START) { try { return handleRedirect(httpMethod, event); } catch (Exception e) { ep = new DefaultExceptionPayload(new DispatchException(event, getEndpoint(), e)); return getResponseFromMethod(httpMethod, ep); } } releaseConn = httpMethod.getResponseBodyAsStream() == null; return getResponseFromMethod(httpMethod, ep); } catch (Exception e) { releaseConn = true; if (e instanceof DispatchException) { throw (DispatchException) e; } throw new DispatchException(event, getEndpoint(), e); } finally { if (releaseConn) { httpMethod.releaseConnection(); } } }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
protected MuleMessage handleRedirect(HttpMethod method, MuleEvent event) throws HttpResponseException, MuleException, IOException { String followRedirects = (String) endpoint.getProperty("followRedirects"); if (followRedirects == null || "false".equalsIgnoreCase(followRedirects)) { if (logger.isInfoEnabled()) { logger.info("Received a redirect, but followRedirects=false. Response code: " + method.getStatusCode() + " " + method.getStatusText()); }/*w ww.j a v a 2 s .c o m*/ return getResponseFromMethod(method, null); } Header locationHeader = method.getResponseHeader(HttpConstants.HEADER_LOCATION); if (locationHeader == null) { throw new HttpResponseException(method.getStatusText(), method.getStatusCode()); } OutboundEndpoint out = new EndpointURIEndpointBuilder(locationHeader.getValue(), httpConnector.getMuleContext()).buildOutboundEndpoint(); MuleEvent result = out.process(event); if (result != null && !VoidMuleEvent.getInstance().equals(result)) { return result.getMessage(); } else { return null; } }
From source file:org.mule.transport.http.HttpClientMessageDispatcher.java
protected boolean returnException(MuleEvent event, HttpMethod httpMethod) { String disableCheck = event.getMessage() .getInvocationProperty(HttpConnector.HTTP_DISABLE_STATUS_CODE_EXCEPTION_CHECK); if (disableCheck == null) { disableCheck = event.getMessage() .getOutboundProperty(HttpConnector.HTTP_DISABLE_STATUS_CODE_EXCEPTION_CHECK); }//from w w w . j a va 2 s .c om return httpMethod.getStatusCode() >= ERROR_STATUS_CODE_RANGE_START && !BooleanUtils.toBoolean(disableCheck); }
From source file:org.mule.transport.http.HttpClientMessageRequester.java
/** * Make a specific request to the underlying transport * * @param timeout the maximum time the operation should block before returning. * The call should return immediately if there is data available. If * no data becomes available before the timeout elapses, null will be * returned/*from w w w.j a v a 2 s . c o m*/ * @return the result of the request wrapped in a MuleMessage object. Null will be * returned if no data was avaialable * @throws Exception if the call to the underlying protocal cuases an exception */ protected MuleMessage doRequest(long timeout) throws Exception { HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress()); connector.setupClientAuthorization(null, httpMethod, client, endpoint); boolean releaseConn = false; try { HttpClient client = new HttpClient(); client.executeMethod(httpMethod); if (httpMethod.getStatusCode() == HttpStatus.SC_OK) { MuleMessage res = (MuleMessage) receiveTransformer.transform(httpMethod); if (StringUtils.EMPTY.equals(res.getPayload())) { releaseConn = true; } return res; } else { releaseConn = true; throw new ReceiveException( HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint, timeout); } } catch (ReceiveException e) { releaseConn = true; throw e; } catch (Exception e) { releaseConn = true; throw new ReceiveException(endpoint, timeout, e); } finally { if (releaseConn) { httpMethod.releaseConnection(); } } }
From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java
private HttpMethod createMockHttpMethod(String method, InputStream body, String uri, Header[] headers) throws Exception { HttpMethod httpMethod = mock(HttpMethod.class); when(httpMethod.getName()).thenReturn(method); when(httpMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 200 OK")); when(httpMethod.getStatusCode()).thenReturn(HttpConstants.SC_OK); when(httpMethod.getURI()).thenReturn(new URI(uri, false)); when(httpMethod.getResponseHeaders()).thenReturn(headers); when(httpMethod.getResponseBodyAsStream()).thenReturn(body); return httpMethod; }