Example usage for org.apache.commons.httpclient HttpClient executeMethod

List of usage examples for org.apache.commons.httpclient HttpClient executeMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient executeMethod.

Prototype

public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException 

Source Link

Usage

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

private static XNATExperimentList invokeXNATDICOMExperimentsQuery(String sessionID,
        String xnatDICOMExperimentsQueryURL) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(xnatDICOMExperimentsQueryURL);
    int xnatStatusCode;

    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);

    try {/* www .ja  v  a  2  s .  c  o m*/
        xnatStatusCode = client.executeMethod(method);
    } catch (IOException e) {
        log.warning("Error performing XNAT experiment query " + xnatDICOMExperimentsQueryURL, e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    return processXNATExperimentsQueryResponse(method, xnatStatusCode); // Will release connection
}

From source file:edu.ku.brc.af.tasks.StatsTrackerTask.java

/**
 * Connects to the update/usage tracking server to get the latest version info and/or send the usage stats.
 * @param url/*from www  . ja  v  a  2s  .  c  o m*/
 * @param postParams
 * @param userAgentName
 * @throws Exception if an IO error occurred or the response couldn't be parsed
 */
public static void sendStats(final String url, final Vector<NameValuePair> postParams,
        final String userAgentName) throws Exception {
    //        System.out.println("--------------------");
    //        for (NameValuePair nvp : postParams)
    //        {
    //            System.out.println(String.format("[%s][%s]", nvp.getName(), nvp.getValue()));
    //        }
    //        System.out.println("--------------------");
    // If the user changes collection before it gets a chance to send the stats
    //if (!AppContextMgr.getInstance().hasContext()) return;

    // check the website for the info about the latest version
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", userAgentName); //$NON-NLS-1$

    PostMethod postMethod = new PostMethod(url);

    // get the POST parameters (which includes usage stats, if we're allowed to send them)
    postMethod.setRequestBody(buildNamePairArray(postParams));

    // connect to the server
    try {
        httpClient.executeMethod(postMethod);

        // get the server response
        @SuppressWarnings("unused")
        String responseString = postMethod.getResponseBodyAsString();

        //if (StringUtils.isNotEmpty(responseString))
        //{
        //    System.err.println(responseString);
        //}

    } catch (java.net.UnknownHostException ex) {
        log.debug("Couldn't reach host.");

    } catch (Exception e) {
        //e.printStackTrace();
        //UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(StatsTrackerTask.class, e);
        throw new ConnectionException(e);
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute method with httpClient.//from  w ww  .  j  a  va  2s . c  o  m
 *
 * @param httpClient Http client instance
 * @param method     Http method
 * @return Http status
 * @throws IOException on error
 */
public static int executeHttpMethod(HttpClient httpClient, HttpMethod method) throws IOException {
    int status = 0;
    try {
        status = httpClient.executeMethod(method);
    } finally {
        method.releaseConnection();
    }
    return status;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute method with httpClient, do not follow 30x redirects.
 *
 * @param httpClient Http client instance
 * @param method     Http method//ww w .j av a 2 s . c o  m
 * @return status
 * @throws IOException on error
 */
public static int executeNoRedirect(HttpClient httpClient, HttpMethod method) throws IOException {
    int status;
    try {
        status = httpClient.executeMethod(method);
        // check NTLM
        if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) {
            LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
            resetMethod(method);
            addNTLM(httpClient);
            status = httpClient.executeMethod(method);
        }
    } finally {
        method.releaseConnection();
    }
    // caller will need to release connection
    return status;
}

From source file:gov.tva.sparky.hbase.RestProxy.java

/**
 * This method adds data to HBase.//www .j  a v  a2  s .  c o  m
 * 
 * @param strTablename
 * @param strRowKey
 * @param strColumn
 * @param strQualifier
 * @param arBytesValue
 * @return
 * @throws URIException
 */
public static boolean InsertHbaseIndexBucket(String strTablename, String strRowKey, String strColumn,
        String strQualifier, byte[] arBytesValue) throws URIException {
    // Configuration
    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");
    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    boolean bResult = false;

    BufferedReader br = null;
    HttpClient client = new HttpClient();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey + "/" + strColumn + ":"
            + strQualifier;

    PostMethod post = new PostMethod(strRestPath);
    post.addRequestHeader("Content-Type", "application/octet-stream");

    RequestEntity entity = new ByteArrayRequestEntity(arBytesValue);
    post.setRequestEntity(entity);

    try {
        int returnCode = client.executeMethod(post);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            // still consume the response body
            post.getResponseBodyAsString();
        } else {
            br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }

            bResult = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception fe) {
                fe.printStackTrace();
            }
        }
    }

    return bResult;
}

From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java

/**
 * Post a request and return the response body
 * /*from w  ww  . j  a va 2  s  . c  o m*/
 * @param httpClient
 *            The HttpClient to use in the post.  This is passed in because
  *            the same client may be used in several posts
 * @param url
 *            the url to post to
 * @param paramMap
 *            map of parameters to add to the post
 * @returns a string holding the response body
 */
public static String post(HttpClient httpClient, String url, HashMap<String, String> paramMap)
        throws IOException, HttpException {

    PostMethod method = new PostMethod(url);

    // Configure the form parameters
    if (paramMap != null) {
        Set<String> paramNames = paramMap.keySet();
        for (String paramName : paramNames) {
            method.addParameter(paramName, paramMap.get(paramName));
        }
    }

    // Execute the POST method
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != -1) {
        String contents = method.getResponseBodyAsString();
        method.releaseConnection();
        return (contents);
    }

    return null;
}

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

private static String invokeXNATQuery(String sessionID, String xnatQueryURL) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(xnatQueryURL);
    int xnatStatusCode;
    log.info("XNATQuery:" + xnatQueryURL);
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);
    try {/*from  w  w w .j a v  a  2 s .c  o m*/
        xnatStatusCode = client.executeMethod(method);
        String xmlResp = method.getResponseBodyAsString(10000);
        log.debug(xmlResp);
        return xmlResp;
    } catch (IOException e) {
        log.warning("Error performing XNAT experiment query " + xnatQueryURL, e);
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:au.org.ala.layers.intersect.IntersectConfig.java

private static void isValidUrl(String url, String desc) {
    HttpClient client = new HttpClient();
    GetMethod get = null;// w w w  . j av a 2s .  co  m

    try {
        get = new GetMethod(url);
        int result = client.executeMethod(get);

        if (result != 200) {
            logger.error("Config error. Property \"" + desc + "\" with value \"" + url
                    + "\"  is not a valid URL.  Error executing GET request, response=" + result);
        }
    } catch (Exception e) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + url
                + "\"  is not a valid URL.  Error executing GET request.");
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

From source file:dk.clarin.tools.userhandle.java

public static String getEmailAddress(HttpServletRequest request, List<FileItem> items, String userHandle,
        String userId) {/*from   w w  w  .ja  v a2 s  .  c o m*/
    /// The user's email
    String userEmail;
    org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
    org.apache.commons.httpclient.methods.GetMethod method;
    String res = null;
    method = null;
    try {
        method = new org.apache.commons.httpclient.methods.GetMethod(
                ToolsProperties.coreServer + "/aa/user-account/" + userId + "/resources/attributes/email");
        method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
        method.setFollowRedirects(false);
        httpClient.executeMethod(method);
        if (method.getStatusCode() != 200) {
            logger.error("Wrong return code. The user's email could not be found! reply: " + res);
            reason = "The user email could not be found!";
            userEmail = null;
        } else {
            String ResponseBody = method.getResponseBodyAsString();
            userEmail = ResponseBody.replaceAll("\r\n", "").replaceAll("<.+?>", "").trim();
            if (userEmail == null || userEmail.length() < 3) {
                logger.error("The user's email could not be found! reply: " + res);
                logger.error(
                        "userHandle " + userHandle + ", userId " + userId + ", ResponseBody " + ResponseBody);
                reason = "The user email could not be found!";
                userEmail = null;
            }
        }
    } catch (IOException e) {
        logger.error("Could not contact the eSciDoc server");
        reason = "Could not contact the eSciDoc server";
        userEmail = null;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    /*
    Dangerous, can be forged!
            if(userEmail == null)
    {
    String [] tmp = request.getParameterValues("ContactEmail");
    if(tmp != null)
        userEmail = tmp[0];
    }
    */
    /*
            if(userEmail == null)
    {
    userEmail = getParmFromMultipartFormData(request,"ContactEmail");
    }
    */
    if (userEmail != null) {
        reason = null;
        logger.debug("user email: " + userEmail);
    }

    return userEmail;
}

From source file:com.carrotsearch.util.httpclient.HttpUtils.java

/**
 * Opens a HTTP/1.1 connection to the given URL using the GET method, decompresses
 * compressed response streams, if supported by the server.
 * /*from w ww  .  jav  a  2 s.  com*/
 * @param url The URL to open. The URL must be properly escaped, this method will
 *            <b>not</b> perform any escaping.
 * @param params Query string parameters to be attached to the url.
 * @param headers Any extra HTTP headers to add to the request.
 * @return The {@link HttpUtils.Response} object. Note that entire payload is read and
 *         buffered so that the HTTP connection can be closed when leaving this
 *         method.
 */
public static Response doGET(String url, Collection<NameValuePair> params, Collection<Header> headers)
        throws HttpException, IOException {
    final HttpClient client = HttpClientFactory.getTimeoutingClient();
    client.getParams().setVersion(HttpVersion.HTTP_1_1);

    final GetMethod request = new GetMethod();
    final Response response = new Response();
    try {
        request.setURI(new URI(url, true));

        if (params != null) {
            request.setQueryString(params.toArray(new NameValuePair[params.size()]));
        }

        request.setRequestHeader(HttpHeaders.URL_ENCODED);
        request.setRequestHeader(HttpHeaders.GZIP_ENCODING);
        if (headers != null) {
            for (Header header : headers)
                request.setRequestHeader(header);
        }

        Logger.getLogger(HttpUtils.class).debug("GET: " + request.getURI());

        final int statusCode = client.executeMethod(request);
        response.status = statusCode;

        InputStream stream = request.getResponseBodyAsStream();
        final Header encoded = request.getResponseHeader("Content-Encoding");
        if (encoded != null && "gzip".equalsIgnoreCase(encoded.getValue())) {
            stream = new GZIPInputStream(stream);
            response.compression = COMPRESSION_GZIP;
        } else {
            response.compression = COMPRESSION_NONE;
        }

        final Header[] respHeaders = request.getResponseHeaders();
        response.headers = new String[respHeaders.length][];
        for (int i = 0; i < respHeaders.length; i++) {
            response.headers[i] = new String[] { respHeaders[i].getName(), respHeaders[i].getValue() };
        }

        response.payload = StreamUtils.readFullyAndClose(stream);
        return response;
    } finally {
        request.releaseConnection();
    }
}