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

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

Introduction

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

Prototype

public HttpClient() 

Source Link

Usage

From source file:com._17od.upm.transport.HTTPTransport.java

public HTTPTransport() {

    client = new HttpClient();

    Boolean acceptSelfSignedCerts = new Boolean(
            Preferences.get(Preferences.ApplicationOptions.HTTPS_ACCEPT_SELFSIGNED_CERTS));
    if (acceptSelfSignedCerts.booleanValue()) {
        // Create a Protcol handler which contains a HTTPS socket factory
        // capable of accepting self signed and otherwise invalid certificates.
        Protocol httpsProtocol = new Protocol("https",
                (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", httpsProtocol);
    }//from  w ww.  j a  v  a 2  s  .co  m

    //Get the proxy settings
    Boolean proxyEnabled = new Boolean(Preferences.get(Preferences.ApplicationOptions.HTTP_PROXY_ENABLED));
    if (proxyEnabled.booleanValue()) {
        String proxyHost = Preferences.get(Preferences.ApplicationOptions.HTTP_PROXY_HOST);
        String proxyPortStr = Preferences.get(Preferences.ApplicationOptions.HTTP_PROXY_PORT);
        String proxyUserName = Preferences.get(Preferences.ApplicationOptions.HTTP_PROXY_USERNAME);
        String proxyPassword = Preferences.get(Preferences.ApplicationOptions.HTTP_PROXY_PASSWORD);
        String decodedPassword = new String(Base64.decodeBase64(proxyPassword.getBytes()));

        if (isNotEmpty(proxyHost)) {
            int proxyPort = 0;
            if (isNotEmpty(proxyPortStr)) {
                proxyPort = Integer.parseInt(proxyPortStr);
                client.getHostConfiguration().setProxy(proxyHost, proxyPort);
                if (isNotEmpty(proxyUserName) && isNotEmpty(proxyPassword)) {
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(proxyUserName, decodedPassword));
                }
            }
        }
    }

}

From source file:edu.ku.brc.services.biogeomancer.BioGeomancer.java

/**
 * Sends a georeferencing request to the BioGeomancer web service.
 * /*from  w  w w .j  a v a  2  s  .c om*/
 * @param id id
 * @param country country
 * @param adm1 country
 * @param adm2 adm2
 * @param localityArg locality
 * @return returns the response body content (as XML)
 * @throws IOException a network error occurred while contacting the BioGeomancer service
 */
public static String getBioGeomancerResponse(final String id, final String country, final String adm1,
        final String adm2, final String localityArg) throws IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod("http://130.132.27.130/cgi-bin/bgm-0.2/batch_test.pl"); //$NON-NLS-1$
    StringBuilder strBuf = new StringBuilder(128);
    strBuf.append("\"" + id + "\","); //$NON-NLS-1$ //$NON-NLS-2$
    strBuf.append("\"" + country + "\","); //$NON-NLS-1$ //$NON-NLS-2$
    strBuf.append("\"" + adm1 + "\","); //$NON-NLS-1$ //$NON-NLS-2$
    strBuf.append("\"" + (adm2 != null ? adm2 : "") + "\","); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    strBuf.append("\"" + localityArg + "\"\r\n"); //$NON-NLS-1$ //$NON-NLS-2$

    NameValuePair[] postData = {
            //new NameValuePair("batchtext", "\"12931\",\"Mexico\",\"Veracruz\",\"\",\"12 km NW of Catemaco\"\r\n"),
            new NameValuePair("batchtext", strBuf.toString()), //$NON-NLS-1$
            new NameValuePair("format", "xml") }; //$NON-NLS-1$ //$NON-NLS-2$

    // the 2.0 beta1 version has a
    // PostMethod.setRequestBody(NameValuePair[])
    // method, as addParameters is deprecated
    postMethod.addParameters(postData);

    httpClient.executeMethod(postMethod);

    InputStream iStream = postMethod.getResponseBodyAsStream();

    StringBuilder sb = new StringBuilder();
    byte[] bytes = new byte[8196];
    int numBytes = 0;
    do {
        numBytes = iStream.read(bytes);
        if (numBytes > 0) {
            sb.append(new String(bytes, 0, numBytes));
        }

    } while (numBytes > 0);

    //release the connection used by the method
    postMethod.releaseConnection();

    return sb.toString();
}

From source file:net.sf.ehcache.constructs.web.filter.SpeedTest.java

/**
 * Time to get 200 Cached Pages/*from   w  w w.j av a 2 s.com*/
 * StopWatch time: 1021ms
 */
public void testSpeedHttpClientCached() throws IOException {
    StopWatch stopWatch = new StopWatch();
    String url = "http://localhost:9080/CachedPage.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    stopWatch.getElapsedTime();
    for (int i = 0; i < 200; i++) {
        httpClient.executeMethod(httpMethod);
        httpMethod.getResponseBodyAsStream();
    }
    long time = stopWatch.getElapsedTime();
    LOG.info("Time for 200 cached page requests: " + time);
}

From source file:com.intranet.intr.sms.SupControllerSms.java

@RequestMapping(value = "SMS.htm", method = RequestMethod.POST)
public String addEstudio_post(@ModelAttribute("mensaje") sms mensaje, BindingResult result, ModelMap map) {
    //String mensaje="";
    try {/*w  ww  .  j  a va  2 s .  c o  m*/
        map.addAttribute("msg", "success");
        HttpClient client = new HttpClient();
        client.setStrictMode(true);
        //Se fija el tiempo maximo de espera de la respuesta del servidor
        client.setTimeout(60000);
        //Se fija el tiempo maximo de espera para conectar con el servidor
        client.setConnectionTimeout(5000);
        PostMethod post = null;
        //Se fija la URL sobre la que enviar la peticion POST
        //Como ejemplo la peticion se enva a www.altiria.net/sustituirPOSTsms
        //Se debe reemplazar la cadena /sustituirPOSTsms por la parte correspondiente
        //de la URL suministrada por Altiria al dar de alta el servicio
        post = new PostMethod("http://www.altiria.net/api/http");
        //Se fija la codificacion de caracteres en la cabecera de la peticion
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //Se crea la lista de parametros a enviar en la peticion POST
        NameValuePair[] parametersList = new NameValuePair[6];
        //XX, YY y ZZ se corresponden con los valores de identificacion del
        //usuario en el sistema.
        parametersList[0] = new NameValuePair("cmd", "sendsms");
        parametersList[1] = new NameValuePair("domainId", "comercial");
        parametersList[2] = new NameValuePair("login", "jfruano");
        parametersList[3] = new NameValuePair("passwd", "wrnkmekt");
        parametersList[4] = new NameValuePair("dest", "34" + mensaje.getNum());
        parametersList[5] = new NameValuePair("msg", "" + mensaje.getTexto());
        //Se rellena el cuerpo de la peticion POST con los parametros
        post.setRequestBody(parametersList);
        int httpstatus = 0;
        String response = null;
        try {
            //Se enva la peticion
            httpstatus = client.executeMethod(post);
            //Se consigue la respuesta
            response = post.getResponseBodyAsString();
        } catch (Exception e) {
            //Habra que prever la captura de excepciones

        } finally {
            //En cualquier caso se cierra la conexion
            post.releaseConnection();
        }
        //Habra que prever posibles errores en la respuesta del servidor
        if (httpstatus != 200) {

        } else {
            //Se procesa la respuesta capturada en la cadena response
        }
    } catch (Exception ex) {
        ex.printStackTrace();

    }
    return "redirect:SMS.htm";

}

From source file:de.mpg.mpdl.inge.util.AdminHelper.java

/**
 * Logs in the given user with the given password.
 * /*from   w  w w  .  j  a v  a 2 s .c  o m*/
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
public static String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = PropertyReader.getLoginUrl();

    int delim1 = frameworkUrl.indexOf("//");
    int delim2 = frameworkUrl.indexOf(":", delim1);

    String host;
    int port;

    if (delim2 > 0) {
        host = frameworkUrl.substring(delim1 + 2, delim2);
        port = Integer.parseInt(frameworkUrl.substring(delim2 + 1));
    } else {
        host = frameworkUrl.substring(delim1 + 2);
        port = 80;
    }
    HttpClient client = new HttpClient();

    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);

    ProxyHelper.executeMethod(client, login);

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    ProxyHelper.executeMethod(client, postMethod);

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(
                    Base64.getDecoder().decode(location.substring(index + 1, location.length())));
            // System.out.println("location: "+location);
            // System.out.println("handle: "+userHandle);
        }
    }

    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:com.stormpath.spring.boot.examples.filter.ReCaptchaFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)
            || !("POST".equalsIgnoreCase(((HttpServletRequest) req).getMethod()))) {
        chain.doFilter(req, res);//from w ww. j  a v  a2 s .  c  om
        return;
    }

    PostMethod method = new PostMethod(RECAPTCHA_URL);
    method.addParameter("secret", RECAPTCHA_SECRET);
    method.addParameter("response", req.getParameter(RECAPTCHA_RESPONSE_PARAM));
    method.addParameter("remoteip", req.getRemoteAddr());

    HttpClient client = new HttpClient();
    client.executeMethod(method);
    BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
    String readLine;
    StringBuffer response = new StringBuffer();
    while (((readLine = br.readLine()) != null)) {
        response.append(readLine);
    }

    JSONObject jsonObject = new JSONObject(response.toString());
    boolean success = jsonObject.getBoolean("success");

    if (success) {
        chain.doFilter(req, res);
    } else {
        ((HttpServletResponse) res).sendError(HttpStatus.BAD_REQUEST.value(), "Bad ReCaptcha");
    }
}

From source file:hydrograph.server.service.HydrographServiceClient.java

public void chcekConnectionStatus() throws IOException {

    HttpClient httpClient = new HttpClient();
    //TODO : add connection details while testing only,remove it once done
    String teradatajson = "{\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}";
    PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/getConnectionStatus");

    //postMethod.addParameter("request_parameters", redshiftjson);
    postMethod.addParameter("request_parameters", teradatajson);

    int response = httpClient.executeMethod(postMethod);
    InputStream inputStream = postMethod.getResponseBodyAsStream();

    byte[] buffer = new byte[1024 * 1024 * 5];
    String path = null;/*from  w  ww .j  a v  a2  s .c  o m*/
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        path = new String(buffer);
    }
    System.out.println("Response of service: " + path);
    System.out.println("==================");
}

From source file:com.dlecan.agreg.AgregResultsBot.java

public AgregResultsBot() {
    client = new HttpClient();
    client.getParams().setParameter("http.useragent", USER_AGENT);

    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("Accept",
            "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"));
    headers.add(new Header("Accept-Language", "fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3"));
    headers.add(new Header("Accept-Encoding", "gzip,deflate"));
    headers.add(new Header("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"));
    client.getParams().setParameter("http.default-headers", headers);
}

From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java

/**
 * Queries an eSciDoc instance/*  ww w . jav a  2s. co  m*/
 * 
 * @param url
 * @param query
 * @param adminUserName
 * @param adminPassword
 * @param frameworkUrl
 * @return
 */
public static Document queryFramework(String url, String query, String adminUserName, String adminPassword,
        String frameworkUrl) {
    try {
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryImpl.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod getMethod = new GetMethod(url + "?query="
                + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                + Base64.encode(
                        getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")));
        System.out.println("Querying <" + url + "?query="
                + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                + Base64.encode(
                        getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")));
        client.executeMethod(getMethod);
        if (getMethod.getStatusCode() == 200) {
            document = documentBuilder.parse(getMethod.getResponseBodyAsStream());
        } else {
            System.out.println("Error querying: Status " + getMethod.getStatusCode() + "\n"
                    + getMethod.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        try {
            System.out.println("Error querying Framework <" + url + "?query="
                    + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                    + Base64.encode(
                            getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))
                    + ">");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
    return null;
}

From source file:com.npower.dm.msm.tools.PackageCheckerImpl.java

public PackageMetaInfo getPackageMetaInfo(String url) throws DMException {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    PackageMetaInfo metaInfo = new PackageMetaInfo();
    metaInfo.setUrl(url);/*from w  ww. java 2 s.  c  o m*/
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        metaInfo.setServerStatus(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            // System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));

        Header mimeType = method.getResponseHeader("Content-Type");
        if (mimeType != null) {
            metaInfo.setMimeType(mimeType.getValue());
        }

        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength != null && StringUtils.isNotEmpty(contentLength.getValue())) {
            metaInfo.setSize(Integer.parseInt(contentLength.getValue()));
        }

    } catch (HttpException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return metaInfo;
}