Example usage for org.apache.commons.httpclient HttpMethod getStatusLine

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusLine

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getStatusLine.

Prototype

public abstract StatusLine getStatusLine();

Source Link

Usage

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }//w w w  .  jav  a2 s  .c o  m
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.commons.httpclient.demo.MultiThreadedHttpDemo.java

public static void main(String[] args) {
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient client = new HttpClient(connectionManager);
    ///* ww w .  j a  va  2 s  .c o m*/
    //client.getHostConfiguration().setProxy("90.0.12.21",808);
    //GETHTTPSURLhttphttps
    HttpMethod method = new GetMethod("http://java.sun.com");
    //POST
    //HttpMethod method = new PostMethod("http://java.sun.com");
    try {
        client.executeMethod(method);
    } catch (IOException ex) {
    }
    //
    System.out.println("===================================");
    System.out.println("");
    System.out.println(method.getStatusLine());
    System.out.println("===================================");
    //
    System.out.println("===================================");
    System.out.println(":");
    try {
        System.out.println(method.getResponseBodyAsString());
    } catch (IOException ex1) {
    }
    System.out.println("===================================");
    //
    method.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.SimpleClient.java

public static void main(String[] args) throws IOException {
    HttpClient client = new HttpClient();
    ///*  ww w .  j a v  a2s . c o  m*/
    client.getHostConfiguration().setProxy("90.0.12.21", 808);
    //GETHTTPSURLhttphttps
    HttpMethod method = new GetMethod("http://java.sun.com");
    //POST
    //HttpMethod method = new PostMethod("http://java.sun.com");
    client.executeMethod(method);
    //
    System.out.println("===================================");
    System.out.println("");
    System.out.println(method.getStatusLine());
    System.out.println("===================================");
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(method.getResponseBodyAsString());
    System.out.println("===================================");
    //
    method.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.SimpleHttpClient.java

public static void main(String[] args) throws IOException {

    HttpClient client = new HttpClient();
    ////from ww w  .  j  a  v a2  s  .co m
    //client.getHostConfiguration().setProxy("90.0.12.21",808);

    client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http");
    HttpMethod method = getPostMethod(); //POST
    //HttpMethod method = getPostMethod(); //GET
    client.executeMethod(method);

    //
    System.out.println("===================================");
    System.out.println("");
    System.out.println(method.getStatusLine());
    System.out.println("===================================");

    //
    String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(response);
    System.out.println("===================================");

    method.releaseConnection();
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Gets the ResponseHeaders/*from w  w w .ja  va  2s.  c  om*/
 *
 * @param method the method used to perform the request
 * @return string containing the headers, one per line
 */
protected String getResponseHeaders(HttpMethod method) {
    StringBuilder headerBuf = new StringBuilder();
    org.apache.commons.httpclient.Header[] rh = method.getResponseHeaders();
    headerBuf.append(method.getStatusLine());// header[0] is not the status line...
    headerBuf.append("\n"); // $NON-NLS-1$

    for (Header responseHeader : rh) {
        String key = responseHeader.getName();
        headerBuf.append(key);
        headerBuf.append(": "); // $NON-NLS-1$
        headerBuf.append(responseHeader.getValue());
        headerBuf.append("\n"); // $NON-NLS-1$
    }
    return headerBuf.toString();
}

From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java

/**
 * Checks the given link.//  w ww  . jav a  2s.  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.HttpClientHelper.java

/**
 * @param method//from   ww  w .jav  a  2  s.  c  om
 * @param bodyIsXml if true the body will be parsed as xml else the body will be inserted as string
 * @return
 * @throws IOException
 */
public static Element prepareDetailsElement(HttpMethod method, boolean bodyIsXml) throws IOException {
    Document doc = DOMUtils.newDocument();
    Element detailsEl = doc.createElementNS(null, "details");
    Element statusLineEl = statusLineToElement(doc, method.getStatusLine());
    detailsEl.appendChild(statusLineEl);

    // set the body if any
    final InputStream bodyAsStream = method.getResponseBodyAsStream();
    if (bodyAsStream != null) {
        Element bodyEl = doc.createElementNS(null, "responseBody");
        detailsEl.appendChild(bodyEl);
        // first, try to parse the body as xml
        // if it fails, put it as string in the body element
        boolean exceptionDuringParsing = false;
        if (bodyIsXml) {
            try {
                Element parsedBodyEl = DOMUtils.parse(bodyAsStream).getDocumentElement();
                bodyEl.appendChild(parsedBodyEl);
            } catch (Exception e) {
                String errmsg = "Unable to parse the response body as xml. Body will be inserted as string.";
                if (log.isDebugEnabled())
                    log.debug(errmsg, e);
                exceptionDuringParsing = true;
            }
        }
        if (!bodyIsXml || exceptionDuringParsing) {
            bodyEl.setTextContent(method.getResponseBodyAsString());
        }
    }
    return detailsEl;
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

/**
 * Build a "details" element that looks like this:
 *
 * @param method// www. ja  v a2s.  com
 * @return
 * @throws IOException
 */
public static Element prepareDetailsElement(HttpMethod method) {
    Header h = method.getResponseHeader("Content-Type");
    String receivedType = h != null ? h.getValue() : null;
    boolean bodyIsXml = receivedType != null && HttpUtils.isXml(receivedType);

    Document doc = DOMUtils.newDocument();
    Element detailsEl = doc.createElementNS(null, "details");
    Element statusLineEl = statusLineToElement(doc, method.getStatusLine());
    detailsEl.appendChild(statusLineEl);

    // set the body if any
    try {
        final String body = method.getResponseBodyAsString();
        if (StringUtils.isNotEmpty(body)) {
            Element bodyEl = doc.createElementNS(null, "responseBody");
            detailsEl.appendChild(bodyEl);
            // first, try to parse the body as xml
            // if it fails, put it as string in the body element
            boolean exceptionDuringParsing = false;
            if (bodyIsXml) {
                try {
                    Element parsedBodyEl = DOMUtils.stringToDOM(body);
                    bodyEl.appendChild(doc.importNode(parsedBodyEl, true));
                } catch (Exception e) {
                    String errmsg = "Unable to parse the response body as xml. Body will be inserted as string.";
                    if (log.isDebugEnabled())
                        log.debug(errmsg, e);
                    exceptionDuringParsing = true;
                }
            }
            if (!bodyIsXml || exceptionDuringParsing) {
                bodyEl.setTextContent(body);
            }
        }
    } catch (IOException e) {
        if (log.isWarnEnabled())
            log.warn("Exception while loading response body", e);
    }
    return detailsEl;
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

public static String responseToString(HttpMethod m) {
    StringBuilder sb = new StringBuilder(256);
    try {//w  w  w  .  j  av a 2 s  .  c  o m
        sb.append("HTTP Response Details: \n").append(m.getName()).append(" ").append(m.getURI());
    } catch (URIException e) {
        // not that important
        if (log.isDebugEnabled())
            log.debug(e);
    }
    sb.append("\nStatus-Line: ").append(m.getStatusLine());
    Header[] headers = m.getResponseHeaders();
    if (headers.length != 0)
        sb.append("\nResponse Headers: ");
    for (int i = 0; i < headers.length; i++) {
        Header h = headers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    try {
        if (StringUtils.isNotEmpty(m.getResponseBodyAsString())) {
            sb.append("\nResponse Entity:\n").append(m.getResponseBodyAsString());
        }
    } catch (IOException e) {
        log.error(e);
    }
    Header[] footers = m.getResponseFooters();
    if (footers.length != 0)
        sb.append("\nResponse Footers: ");
    for (int i = 0; i < footers.length; i++) {
        Header h = footers[i];
        sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue());
    }
    return sb.toString();
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * Process the HTTP Response Headers.//from   w  w w. j av a2  s .c om
 * <p/>
 * First go through the list of {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :header} elements included in the output binding.
 * For each of them, set the header value as the value of the message part.
 * <p/>
 * Then add all HTTP headers as header part in the message. The name of the header would be the part name.
 * <p/>
 * Finally, insert a header names 'Status-Line'. This header contains an element as returned by {@link HttpHelper#statusLineToElement(String)} .
 *
 * @param odeMessage
 * @param method
 * @param operationDef
 */
public void extractHttpResponseHeaders(org.apache.ode.bpel.iapi.Message odeMessage, HttpMethod method,
        Operation operationDef) {
    Message messageDef = operationDef.getOutput().getMessage();

    BindingOutput outputBinding = binding.getBindingOperation(operationDef.getName(),
            operationDef.getInput().getName(), operationDef.getOutput().getName()).getBindingOutput();
    Collection<UnknownExtensibilityElement> headerBindings = WsdlUtils
            .getHttpHeaders(outputBinding.getExtensibilityElements());

    // iterate through the list of header bindings
    // and set the message parts accordingly
    for (Iterator<UnknownExtensibilityElement> iterator = headerBindings.iterator(); iterator.hasNext();) {
        Element binding = iterator.next().getElement();
        String partName = binding.getAttribute("part");
        String headerName = binding.getAttribute("name");

        Part part = messageDef.getPart(partName);
        if (StringUtils.isNotEmpty(partName)) {
            Header responseHeader = method.getResponseHeader(headerName);
            // if the response header is not set, just skip it. no need to fail.
            if (responseHeader != null) {
                odeMessage.setPart(partName, createPartElement(part, responseHeader.getValue()));
            }
        } else {
            String errMsg = "Invalid binding: missing required attribute! Part name: "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "part");
            if (log.isErrorEnabled())
                log.error(errMsg);
            throw new RuntimeException(errMsg);
        }
    }

    // add all HTTP response headers (in their condensed form) into the message as header parts
    Set<String> headerNames = new HashSet<String>();
    for (Header header : method.getResponseHeaders())
        headerNames.add(header.getName());
    for (String hname : headerNames)
        odeMessage.setHeaderPart(hname, method.getResponseHeader(hname).getValue());

    // make the status line information available as a single element
    odeMessage.setHeaderPart("Status-Line", HttpHelper.statusLineToElement(method.getStatusLine()));
}