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

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

Introduction

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

Prototype

public void setTimeout(int paramInt)

Source Link

Usage

From source file:com.intellij.openapi.paths.WebReferencesAnnotatorBase.java

private static MyFetchResult doCheckUrl(String url) {
    final HttpClient client = new HttpClient();
    client.setTimeout(3000);
    client.setConnectionTimeout(3000);/*  w ww. j a va 2  s . co m*/
    // see http://hc.apache.org/httpclient-3.x/cookies.html
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    try {
        final GetMethod method = new GetMethod(url);
        final int code = client.executeMethod(method);

        return code == HttpStatus.SC_OK || code == HttpStatus.SC_REQUEST_TIMEOUT ? MyFetchResult.OK
                : MyFetchResult.NONEXISTENCE;
    } catch (UnknownHostException e) {
        LOG.info(e);
        return MyFetchResult.UNKNOWN_HOST;
    } catch (IOException e) {
        LOG.info(e);
        return MyFetchResult.OK;
    } catch (IllegalArgumentException e) {
        LOG.debug(e);
        return MyFetchResult.OK;
    }
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String loadResource(String url, String extra, String username, String password,
        String resourcepath) {/*from w  ww  . ja v  a 2  s . c  o m*/
    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    File input = new File(resourcepath);

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    //put.addRequestHeader("Content-type", "application/zip");

    // Request content will be retrieved directly 
    // from the input stream 
    RequestEntity entity = new FileRequestEntity(input, "application/zip");
    put.setRequestEntity(entity);

    // Execute the request 
    try {
        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        e.printStackTrace(System.out);
        output = "0: " + e.getMessage();
    } finally {
        // Release current connection to the connection pool once you are done 
        put.releaseConnection();
    }

    return output;

}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String loadSld(String url, String extra, String username, String password, String resourcepath) {
    System.out.println("loadSld url:" + url);
    System.out.println("path:" + resourcepath);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);/*ww w.j  a v a 2 s  .  c om*/
    client.setTimeout(60000);

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    client.getParams().setAuthenticationPreemptive(true);

    File input = new File(resourcepath);

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    // Request content will be retrieved directly
    // from the input stream
    RequestEntity entity = new FileRequestEntity(input, "application/vnd.ogc.sld+xml");
    put.setRequestEntity(entity);

    // Execute the request
    try {
        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        e.printStackTrace(System.out);
        output = "0: " + e.getMessage();
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String loadCreateStyle(String url, String extra, String username, String password, String name) {
    System.out.println("loadCreateStyle url:" + url);
    System.out.println("name:" + name);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);//from w w  w . j  a va  2s . c o m
    client.setTimeout(60000);

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PostMethod post = new PostMethod(url);
    post.setDoAuthentication(true);

    // Execute the request
    try {
        // Request content will be retrieved directly
        // from the input stream
        File file = File.createTempFile("sld", "xml");
        FileWriter fw = new FileWriter(file);
        fw.append("<style><name>" + name + "</name><filename>" + name + ".sld</filename></style>");
        fw.close();
        RequestEntity entity = new FileRequestEntity(file, "text/xml");
        post.setRequestEntity(entity);

        int result = client.executeMethod(post);

        output = result + ": " + post.getResponseBodyAsString();

    } catch (Exception e) {
        e.printStackTrace(System.out);
        output = "0: " + e.getMessage();
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }

    return output;
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String assignSld(String url, String extra, String username, String password, String data) {
    System.out.println("assignSld url:" + url);
    System.out.println("data:" + data);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);/*from  w w  w.  ja va  2s  . c  o m*/
    client.setTimeout(60000);

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    // Execute the request
    try {
        // Request content will be retrieved directly
        // from the input stream
        File file = File.createTempFile("sld", "xml");
        System.out.println("file:" + file.getPath());
        FileWriter fw = new FileWriter(file);
        fw.append(data);
        fw.close();
        RequestEntity entity = new FileRequestEntity(file, "text/xml");
        put.setRequestEntity(entity);

        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

/**
 * sends a PUT or POST call to a URL using authentication and including a
 * file upload/*  ww w . jav  a2s  . c o  m*/
 *
 * @param type         one of UploadSpatialResource.PUT for a PUT call or
 *                     UploadSpatialResource.POST for a POST call
 * @param url          URL for PUT/POST call
 * @param username     account username for authentication
 * @param password     account password for authentication
 * @param resourcepath local path to file to upload, null for no file to
 *                     upload
 * @param contenttype  file MIME content type
 * @return server response status code as String or empty String if
 * unsuccessful
 */
public static String httpCall(int type, String url, String username, String password, String resourcepath,
        String contenttype) {
    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    RequestEntity entity = null;
    if (resourcepath != null) {
        File input = new File(resourcepath);
        entity = new FileRequestEntity(input, contenttype);
    }

    HttpMethod call = null;
    ;
    if (type == PUT) {
        PutMethod put = new PutMethod(url);
        put.setDoAuthentication(true);
        if (entity != null) {
            put.setRequestEntity(entity);
        }
        call = put;
    } else if (type == POST) {
        PostMethod post = new PostMethod(url);
        if (entity != null) {
            post.setRequestEntity(entity);
        }
        call = post;
    } else {
        //SpatialLogger.log("UploadSpatialResource", "invalid type: " + type);
        return output;
    }

    // Execute the request 
    try {
        int result = client.executeMethod(call);

        output = result + ": " + call.getResponseBodyAsString();
    } catch (Exception e) {
        //SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url);
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done 
        call.releaseConnection();
    }

    return output;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static void setTimeout(HttpClient client, long timeout) {
    if (timeout > 0) {
        client.setConnectionTimeout((int) timeout);
        client.setTimeout((int) timeout);
    }/*from   w  w  w  . j a va2 s .  c o  m*/
}

From source file:com.bigrocksoftware.metarparser.MetarFetcher.java

public static String fetch(String station, int timeout) {
    metarData = null;//from  ww w.j  av  a 2s.  c om

    // create the http client
    HttpClient client = new HttpClient();

    // set the timeout is specified
    if (timeout != 0) {
        log.debug("MetarFetch: setting timeout to '" + timeout + "' milliseconds");
        long start = System.currentTimeMillis();
        client.setConnectionTimeout(timeout);
        long end = System.currentTimeMillis();
        if (end - start < timeout) {
            client.setTimeout((int) (end - start));
        } else {
            return null;
        }
    }

    // create the http method we will use
    HttpMethod method = new GetMethod(httpMetarURL + station + ".TXT");

    // connect to the NOAA site, retrying up to the specified num
    int statusCode = -1;
    //for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
    try {
        // execute the get method
        log.debug("MetarFetcher: downloading data for station '" + station + "'");
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log.error("a recoverable exception occurred, " + "retrying." + e.getMessage());
    } catch (IOException e) {
        log.error("failed to download file: " + e);
    }
    //}

    // check that we didn't run out of retries
    if (statusCode != HttpStatus.SC_OK) {
        log.error("failed to download station data for '" + station + "'");
        return null;
    } else {
        // read the response body
        byte[] responseBody = method.getResponseBody();

        // release the connection
        method.releaseConnection();

        // deal with the response.
        // FIXME - ensure we use the correct character encoding here
        metarData = new String(responseBody) + "\n";
        log.debug("MetarFetcher: metar data: " + metarData);
    }

    return metarData;
}

From source file:com.liferay.util.Http.java

public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException {

    byte[] byteArray = null;

    HttpMethod method = null;/*from   w ww .  ja va2s  . co  m*/

    try {
        HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

        if (location == null) {
            return byteArray;
        } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) {

            location = HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfig = new HostConfiguration();

        hostConfig.setHost(new URI(location));

        if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) {
            hostConfig.setProxy(PROXY_HOST, PROXY_PORT);
        }

        client.setHostConfiguration(hostConfig);
        client.setConnectionTimeout(5000);
        client.setTimeout(5000);

        if (cookies != null && cookies.length > 0) {
            HttpState state = new HttpState();

            state.addCookies(cookies);
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);

            client.setState(state);
        }

        if (post) {
            method = new PostMethod(location);
        } else {
            method = new GetMethod(location);
        }

        method.setFollowRedirects(true);

        client.executeMethod(method);

        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            return URLtoByteArray(locationHeader.getValue(), cookies, post);
        }

        InputStream is = method.getResponseBodyAsStream();

        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];

            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {

                buffer.write(bytes, 0, i);
            }

            byteArray = buffer.toByteArray();

            is.close();
            buffer.close();
        }

        return byteArray;
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception e) {
            Logger.error(Http.class, e.getMessage(), e);
        }
    }
}

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

@RequestMapping(value = "ESMS.htm", method = RequestMethod.POST)
public String addEstudio_post(@ModelAttribute("mensaje") sms mensaje, BindingResult result, ModelMap map) {
    try {/*from w  ww  . java  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:ESMS.htm";

}