List of usage examples for org.apache.commons.httpclient HttpMethod getStatusCode
public abstract int getStatusCode();
From source file:org.apache.abdera.protocol.client.AbderaClient.java
/** * Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a * server (e.g. PATCH, LOCK, etc)/*from w w w. j av a2 s. c o m*/ * * @param method The HTTP method * @param uri The request URI * @param entity A RequestEntity object providing the payload for the request * @param options The Request Options */ public ClientResponse execute(String method, String uri, RequestEntity entity, RequestOptions options) { boolean usecache = useCache(method, options); options = options != null ? options : getDefaultRequestOptions(); try { Cache cache = getCache(); CachedResponse cached_response = cache.get(uri); switch (getCacheDisposition(usecache, uri, options, cached_response)) { case FRESH: // CACHE HIT: FRESH if (cached_response != null) return checkRequestException(cached_response, options); case STALE: // CACHE HIT: STALE // revalidate the cached entry if (cached_response != null) { if (cached_response.getEntityTag() != null) options.setIfNoneMatch(cached_response.getEntityTag().toString()); else if (cached_response.getLastModified() != null) options.setIfModifiedSince(cached_response.getLastModified()); else options.setNoCache(true); } default: // CACHE MISS HttpMethod httpMethod = MethodHelper.createMethod(method, uri, entity, options); client.executeMethod(httpMethod); if (usecache && (httpMethod.getStatusCode() == 304 || httpMethod.getStatusCode() == 412) && cached_response != null) return cached_response; ClientResponse response = new CommonsResponse(abdera, httpMethod); response = options.getUseLocalCache() ? response = cache.update(uri, options, response, cached_response) : response; return checkRequestException(response, options); } } catch (RuntimeException r) { throw r; } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * Collect the HTTP header information and set them in the message context * //from w ww . j ava2s . com * @param method * HttpMethodBase from which to get information * @param msgContext * the MessageContext in which to place the information... OR * NOT! * @throws AxisFault * if problems occur */ protected void obtainHTTPHeaderInformation(Object httpMethodBase, MessageContext msgContext) throws AxisFault { HttpMethod method; if (httpMethodBase instanceof HttpMethodBase) { method = (HttpMethod) httpMethodBase; } else { return; } // Set RESPONSE properties onto the REQUEST message context. They will // need to be copied off the request context onto // the response context elsewhere, for example in the // OutInOperationClient. Map transportHeaders = new HTTPTransportHeaders(method.getResponseHeaders()); msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, transportHeaders); msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, new Integer(method.getStatusCode())); Header header = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (header != null) { HeaderElement[] headers = header.getElements(); MessageContext inMessageContext = msgContext.getOperationContext() .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); Object contentType = header.getValue(); Object charSetEnc = null; for (int i = 0; i < headers.length; i++) { NameValuePair charsetEnc = headers[i].getParameterByName(HTTPConstants.CHAR_SET_ENCODING); if (charsetEnc != null) { charSetEnc = charsetEnc.getValue(); } } if (inMessageContext != null) { inMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType); inMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } else { // Transport details will be stored in a HashMap so that anybody // interested can // retrieve them HashMap transportInfoMap = new HashMap(); transportInfoMap.put(Constants.Configuration.CONTENT_TYPE, contentType); transportInfoMap.put(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); // the HashMap is stored in the outgoing message. msgContext.setProperty(Constants.Configuration.TRANSPORT_INFO_MAP, transportInfoMap); } } String sessionCookie = null; // Process old style headers first Header[] cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE); String customCoookiId = (String) msgContext.getProperty(Constants.CUSTOM_COOKIE_ID); for (int i = 0; i < cookieHeaders.length; i++) { HeaderElement[] elements = cookieHeaders[i].getElements(); for (int e = 0; e < elements.length; e++) { HeaderElement element = elements[e]; if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } } } // Overwrite old style cookies with new style ones if present cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE2); for (int i = 0; i < cookieHeaders.length; i++) { HeaderElement[] elements = cookieHeaders[i].getElements(); for (int e = 0; e < elements.length; e++) { HeaderElement element = elements[e]; if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } } } if (sessionCookie != null) { msgContext.getServiceContext().setProperty(HTTPConstants.COOKIE_STRING, sessionCookie); } }
From source file:org.apache.cloudstack.network.element.SspClient.java
private String executeMethod(HttpMethod method) { String apiCallPath = null;// w ww .j av a 2s . co m try { apiCallPath = method.getName() + " " + method.getURI().toString(); } catch (URIException e) { s_logger.error("method getURI failed", e); } String response = null; try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { if (!login()) { return null; } try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } } s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine()); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod emethod = (EntityEnclosingMethod) method; RequestEntity reqEntity = emethod.getRequestEntity(); if (reqEntity instanceof StringRequestEntity) { StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity; s_logger.debug("ssp api request body:" + strReqEntity.getContent()); } else { s_logger.debug("ssp api request body:" + emethod.getRequestEntity()); } } s_logger.debug("ssp api response body:" + response); return response; }
From source file:org.apache.excalibur.source.factories.HTTPClientSource.java
/** * Method to update whether a referenced resource exists, after * executing a particular {@link HttpMethod}. * * <p>REVISIT: exists() would be better called canRead() * or similar, as a resource can exist but not be readable.</p> * * @param method {@link HttpMethod} executed. */// w w w. ja va 2 s . co m private void updateExists(final HttpMethod method) { final int response = method.getStatusCode(); // The following returns true, if the user can successfully get // an InputStream without receiving errors? ie. if we receive a // HTTP 200 (OK), 201 (CREATED), 206 (PARTIAL CONTENT) // REVISIT(MC): need a special way to handle 304 (NOT MODIFIED) // 204 & 205 in the future // resource does not exist if HttpClient returns a 404 or a 410 this.m_exists = (response == HttpStatus.SC_OK || response == HttpStatus.SC_CREATED || response == HttpStatus.SC_PARTIAL_CONTENT); }
From source file:org.apache.hadoop.fs.swift.exceptions.SwiftInvalidResponseException.java
public SwiftInvalidResponseException(String message, String operation, URI uri, HttpMethod method) { super(message); this.statusCode = method.getStatusCode(); this.operation = operation; this.uri = uri; String bodyAsString;// www . j a v a 2 s. com try { bodyAsString = method.getResponseBodyAsString(); if (bodyAsString == null) { bodyAsString = ""; } } catch (IOException e) { bodyAsString = ""; } this.body = bodyAsString; }
From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** {@inheritDoc} */ public LinkValidationResult validateLink(LinkValidationItem lvi) { if (this.cl == null) { initHttpClient();/* w w w . j a v a 2 s .co m*/ } if (this.http.getHttpClientParameters() != null) { for (Map.Entry<Object, Object> entry : this.http.getHttpClientParameters().entrySet()) { if (entry.getValue() != null) { System.setProperty(entry.getKey().toString(), entry.getValue().toString()); } } } // Some web servers don't allow the default user-agent sent by httpClient System.setProperty(HttpMethodParams.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); this.cl.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); String link = lvi.getLink(); String anchor = ""; int idx = link.indexOf('#'); if (idx != -1) { anchor = link.substring(idx + 1); link = link.substring(0, idx); } try { if (link.startsWith("/")) { if (getBaseURL() == null) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot check link [" + link + "] in page [" + lvi.getSource() + "], as no base URL has been set!"); } return new LinkValidationResult(LinkcheckFileResult.WARNING_LEVEL, false, "No base URL specified"); } link = getBaseURL() + link; } HttpMethod hm = null; try { hm = checkLink(link, 0); } catch (Throwable t) { if (LOG.isDebugEnabled()) { LOG.debug("Received: [" + t + "] for [" + link + "] in page [" + lvi.getSource() + "]", t); } return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, t.getClass().getName() + " : " + t.getMessage()); } if (hm == null) { return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, "Cannot retreive HTTP Status"); } if (hm.getStatusCode() == HttpStatus.SC_OK) { // lets check if the anchor is present if (anchor.length() > 0) { String content = hm.getResponseBodyAsString(); if (!Anchors.matchesAnchor(content, anchor)) { return new HTTPLinkValidationResult(LinkcheckFileResult.VALID_LEVEL, false, "Missing anchor '" + anchor + "'"); } } return new HTTPLinkValidationResult(LinkcheckFileResult.VALID_LEVEL, true, hm.getStatusCode(), hm.getStatusText()); } String msg = "Received: [" + hm.getStatusCode() + "] for [" + link + "] in page [" + lvi.getSource() + "]"; // If there's a redirection ... add a warning if (hm.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || hm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || hm.getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { LOG.warn(msg); return new HTTPLinkValidationResult(LinkcheckFileResult.WARNING_LEVEL, true, hm.getStatusCode(), hm.getStatusText()); } LOG.debug(msg); return new HTTPLinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, hm.getStatusCode(), hm.getStatusText()); } catch (Throwable t) { String msg = "Received: [" + t + "] for [" + link + "] in page [" + lvi.getSource() + "]"; if (LOG.isDebugEnabled()) { LOG.debug(msg, t); } else { LOG.error(msg); } return new LinkValidationResult(LinkcheckFileResult.ERROR_LEVEL, false, t.getMessage()); } finally { System.getProperties().remove(HttpMethodParams.USER_AGENT); if (this.http.getHttpClientParameters() != null) { for (Map.Entry<Object, Object> entry : this.http.getHttpClientParameters().entrySet()) { if (entry.getValue() != null) { System.getProperties().remove(entry.getKey().toString()); } } } } }
From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** * Checks the given link.//w w w. j a v a2 s . c o m * * @param link the link to check. * @param nbRedirect the number of current redirects. * @return HttpMethod * @throws IOException if something goes wrong. */ private HttpMethod checkLink(String link, int nbRedirect) throws IOException { int max = MAX_NB_REDIRECT; if (this.http.getHttpClientParameters() != null && this.http.getHttpClientParameters().get(HttpClientParams.MAX_REDIRECTS) != null) { try { max = Integer .valueOf(this.http.getHttpClientParameters().get(HttpClientParams.MAX_REDIRECTS).toString()) .intValue(); } catch (NumberFormatException e) { if (LOG.isWarnEnabled()) { LOG.warn("HttpClient parameter '" + HttpClientParams.MAX_REDIRECTS + "' is not a number. Ignoring!"); } } } if (nbRedirect > max) { throw new HttpException("Maximum number of redirections (" + max + ") exceeded"); } HttpMethod hm; if (HEAD_METHOD.equalsIgnoreCase(this.http.getMethod())) { hm = new HeadMethod(link); } else if (GET_METHOD.equalsIgnoreCase(this.http.getMethod())) { hm = new GetMethod(link); } else { if (LOG.isErrorEnabled()) { LOG.error("Unsupported method: " + this.http.getMethod() + ", using 'get'."); } hm = new GetMethod(link); } // Default hm.setFollowRedirects(this.http.isFollowRedirects()); try { URL url = new URL(link); cl.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol()); cl.executeMethod(hm); StatusLine sl = hm.getStatusLine(); if (sl == null) { if (LOG.isErrorEnabled()) { LOG.error("Unknown error validating link : " + link); } return null; } if (hm.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || hm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || hm.getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { Header locationHeader = hm.getResponseHeader("location"); if (locationHeader == null) { LOG.error("Site sent redirect, but did not set Location header"); return hm; } String newLink = locationHeader.getValue(); // Be careful to absolute/relative links if (!newLink.startsWith("http://") && !newLink.startsWith("https://")) { if (newLink.startsWith("/")) { URL oldUrl = new URL(link); newLink = oldUrl.getProtocol() + "://" + oldUrl.getHost() + (oldUrl.getPort() > 0 ? ":" + oldUrl.getPort() : "") + newLink; } else { newLink = link + newLink; } } HttpMethod oldHm = hm; if (LOG.isDebugEnabled()) { LOG.debug("[" + link + "] is redirected to [" + newLink + "]"); } oldHm.releaseConnection(); hm = checkLink(newLink, nbRedirect + 1); // Restore the hm to "Moved permanently" | "Moved temporarily" | "Temporary redirect" // if the new location is found to allow us to report it if (hm.getStatusCode() == HttpStatus.SC_OK && nbRedirect == 0) { return oldHm; } } } finally { hm.releaseConnection(); } return hm; }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
public void parseHttpResponse(org.apache.ode.bpel.iapi.Message odeResponse, HttpMethod method, Operation opDef) throws SAXException, IOException { BindingOperation opBinding = binding.getBindingOperation(opDef.getName(), opDef.getInput().getName(), opDef.getOutput().getName()); /* process headers */ extractHttpResponseHeaders(odeResponse, method, opDef); /* process the body if any */ // assumption is made that a response may have at most one body. HttpBindingValidator checks this. MIMEContent outputContent = WsdlUtils .getMimeContent(opBinding.getBindingOutput().getExtensibilityElements()); int status = method.getStatusCode(); boolean xmlExpected = outputContent != null && HttpUtils.isXml(outputContent.getType()); // '202/Accepted' and '204/No Content' status codes explicitly state that there is no body, so we should not fail even if a part is bound to the body response boolean isBodyExpected = outputContent != null; boolean isBodyMandatory = isBodyExpected && bodyAllowed(status) && status != _202_ACCEPTED; final String body; try {/*www.j a v a 2s . co m*/ body = method.getResponseBodyAsString(); } catch (IOException e) { throw new RuntimeException("Unable to get the request body : " + e.getMessage()); } final boolean emptyBody = StringUtils.isEmpty(body); if (emptyBody) { if (isBodyMandatory) { throw new RuntimeException("Response body is mandatory but missing!"); } } else { if (isBodyExpected) { Part partDef = opDef.getOutput().getMessage().getPart(outputContent.getPart()); Element partElement; if (xmlExpected) { Header h = method.getResponseHeader("Content-Type"); String receivedType = h != null ? h.getValue() : null; boolean contentTypeSet = receivedType != null; boolean xmlReceived = contentTypeSet && HttpUtils.isXml(receivedType); // a few checks if (!contentTypeSet) { if (log.isDebugEnabled()) log.debug("Received Response with a body but no 'Content-Type' header!"); } else if (!xmlReceived) { if (log.isDebugEnabled()) log.debug("Xml type was expected but non-xml type received! Expected Content-Type=" + outputContent.getType() + " Received Content-Type=" + receivedType); } // parse the body and create the message part Element bodyElement = DOMUtils.stringToDOM(body); partElement = createPartElement(partDef, bodyElement); } else { // if not xml, process it as text partElement = createPartElement(partDef, body); } // set the part odeResponse.setPart(partDef.getName(), partElement); } else { // the body was not expected but we don't know how to deal with it if (log.isDebugEnabled()) log.debug("Body received but not mapped to any part! Body=\n" + body); } } }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
public Object[] parseFault(PartnerRoleMessageExchange odeMex, HttpMethod method) { Operation opDef = odeMex.getOperation(); BindingOperation opBinding = binding.getBindingOperation(opDef.getName(), opDef.getInput().getName(), opDef.getOutput().getName()); final String body; try {/* w w w . j a v a 2 s .com*/ body = method.getResponseBodyAsString(); } catch (IOException e) { throw new RuntimeException("Unable to get the request body : " + e.getMessage(), e); } Header h = method.getResponseHeader("Content-Type"); String receivedType = h != null ? h.getValue() : null; if (opDef.getFaults().isEmpty()) { throw new RuntimeException("Operation [" + opDef.getName() + "] has no fault. This " + method.getStatusCode() + " error will be considered as a failure."); } else if (opBinding.getBindingFaults().isEmpty()) { throw new RuntimeException( "No fault binding. This " + method.getStatusCode() + " error will be considered as a failure."); } else if (StringUtils.isEmpty(body)) { throw new RuntimeException("No body in the response. This " + method.getStatusCode() + " error will be considered as a failure."); } else if (receivedType != null && !HttpUtils.isXml(receivedType)) { throw new RuntimeException("Response Content-Type [" + receivedType + "] does not describe XML entities. Faults must be XML. This " + method.getStatusCode() + " error will be considered as a failure."); } else { if (receivedType == null) { if (log.isWarnEnabled()) log.warn("[Service: " + serviceName + ", Port: " + portName + ", Operation: " + opDef.getName() + "] Received Response with a body but no 'Content-Type' header! Will try to parse nevertheless."); } // try to parse body final Element bodyElement; try { bodyElement = DOMUtils.stringToDOM(body); } catch (Exception e) { throw new RuntimeException("Unable to parse the response body as xml. This " + method.getStatusCode() + " error will be considered as a failure.", e); } // Guess which fault it is QName bodyName = new QName(bodyElement.getNamespaceURI(), bodyElement.getNodeName()); Fault faultDef = WsdlUtils.inferFault(opDef, bodyName); if (faultDef == null) { throw new RuntimeException("Unknown Fault Type [" + bodyName + "] This " + method.getStatusCode() + " error will be considered as a failure."); } else if (!WsdlUtils.isOdeFault(opBinding.getBindingFault(faultDef.getName()))) { // is this fault bound with ODE extension? throw new RuntimeException("Fault [" + bodyName + "] is not bound with " + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "fault") + ". This " + method.getStatusCode() + " error will be considered as a failure."); } else { // a fault has only one part Part partDef = (Part) faultDef.getMessage().getParts().values().iterator().next(); QName faultName = new QName(definition.getTargetNamespace(), faultDef.getName()); QName faultType = faultDef.getMessage().getQName(); // create the ODE Message now that we know the fault org.apache.ode.bpel.iapi.Message response = odeMex.createMessage(faultType); // build the element to be sent back Element partElement = createPartElement(partDef, bodyElement); response.setPart(partDef.getName(), partElement); // extract and set headers extractHttpResponseHeaders(response, method, opDef); return new Object[] { faultName, response }; } } }
From source file:org.apache.servicemix.http.ServerManagerTest.java
private String requestWithHttpClient(String url, String content) throws Exception { HttpMethod method; if (content != null) { PostMethod post = new PostMethod(url); post.setRequestEntity(new StringRequestEntity(content)); method = post;/*from w w w. j av a2 s. co m*/ } else { GetMethod get = new GetMethod(url); method = get; } new HttpClient().executeMethod(method); if (method.getStatusCode() != 200) { throw new InvalidStatusResponseException(method.getStatusCode()); } return method.getResponseBodyAsString(); }