Example usage for org.apache.commons.httpclient HttpException getMessage

List of usage examples for org.apache.commons.httpclient HttpException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.discursive.jccook.httpclient.GetExample.java

public static void main(String[] args) {
    HttpClient client = new HttpClient();
    String url = "http://www.discursive.com/jccook/";
    HttpMethod method = new GetMethod(url);

    try {//from  w ww .ja v a2 s  .c  om
        client.executeMethod(method);
        String response = method.getResponseBodyAsString();

        System.out.println(response);
    } catch (HttpException he) {
        System.out.println("HTTP Problem: " + he.getMessage());
    } catch (IOException ioe) {
        System.out.println("IO Exeception: " + ioe.getMessage());
    } finally {
        method.releaseConnection();
        method.recycle();
    }
}

From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java

public static void main(String[] args) {

    // test();/* www.  ja v  a  2s . c o m*/
    // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP
    // System.setProperty("proxyPort", "8080");
    // System.setProperty("socksProxyPort", "1080");
    //
    // Authenticator.setDefault(new MyAuthenticator());

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    // Create a method instance.
    GetMethod method = new GetMethod(url);

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //     
    // client.getState().setProxyCredentials(authScope, credentials);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();//w w  w .j a v  a2 s.c o  m
        System.exit(-1);
    }

    Credentials creds = null;
    if (args.length >= 3) {
        creds = new UsernamePasswordCredentials(args[1], args[2]);
    }

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(AuthScope.ANY, creds);
    }

    String url = args[0];
    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();

    System.exit(0);
}

From source file:ExampleP2PHttpClient.java

public static void main(String[] args) {
    // initialize JXTA
    try {/*from www  .ja v a2s . com*/
        // sign in and initialize the JXTA network; profile this peer and create it
        // if it doesn't exist
        P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // register the P2P socket protocol factory
    Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80);
    Protocol.registerProtocol("p2phttp", jxtaHttp);

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 50 seconds
    client.setConnectionTimeout(50000);

    String url = System.getProperty("url");
    if (url == null || url.equals("")) {
        System.out.println("You must provide a URL to access.  For example:");
        System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo");

        System.exit(1);
    }
    System.out.println("Connecting to " + url + "...");

    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();
    method.recycle();

    System.exit(0);
}

From source file:io.aos.protocol.http.commons.CommonsHttpClient.java

public static void get(String url) {

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {// w  ww . ja  va 2s  .  c o m
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }
        byte[] responseBody = method.getResponseBody();
        LOG.debug(new String(responseBody, "UTF-8"));
    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3Util.java

/**
 * ?url?ResponseBody,method=get/*  ww  w. ja  v  a2s .  c  o m*/
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3UtilError.java

/**
 * ?url?ResponseBody,method=get//  w  w  w  .j a v  a2 s. c om
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    // method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3UtilUseManager.java

/**
 * ?url?ResponseBody,method=get//w  ww .  ja v  a2 s  . c  o  m
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient(connectionManager);
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    // method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:de.intranda.goobi.plugins.utils.SRUClient.java

/**
 * Queries the given catalog via Z.3950 (SRU) and returns its response.
 * /*  w  ww  .  j ava2s  .  co m*/
 * @param cat The catalog to query.
 * @param query The query.
 * @param recordSchema The expected record schema.
 * @return Query result XML string.
 */
public static String querySRU(ConfigOpacCatalogue cat, String query, String recordSchema) {
    String ret = null;
    if (query != null && !query.isEmpty()) {
        query = query.trim();
    }

    if (cat != null) {
        String url = "http://";

        url += cat.getAddress();
        url += ":" + cat.getPort();
        url += "/" + cat.getDatabase();
        url += "?version=1.1";
        url += "&operation=searchRetrieve";
        url += "&query=" + query;
        url += "&maximumRecords=5";
        url += "&recordSchema=" + recordSchema;

        logger.debug("SRU URL: " + url);

        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        try {
            client.executeMethod(method);
            ret = method.getResponseBodyAsString();
            if (!method.getResponseCharSet().equalsIgnoreCase(ENCODING)) {
                // If response XML is not UTF-8, re-encode
                ret = convertStringEncoding(ret, method.getResponseCharSet(), ENCODING);
            }
        } catch (HttpException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            method.releaseConnection();
        }
    }

    return ret;
}

From source file:com.dotmarketing.util.UpdateUtil.java

/**
 * @return the new version if found. Null if up to date.
 * @throws DotDataException if an error is encountered
 *///w w w.j  a va 2  s  .  c o m
public static String getNewVersion() throws DotDataException {

    //Loading the update url
    Properties props = loadUpdateProperties();
    String fileUrl = props.getProperty(Constants.PROPERTY_UPDATE_FILE_UPDATE_URL, "");

    Map<String, String> pars = new HashMap<String, String>();
    pars.put("version", ReleaseInfo.getVersion());
    //pars.put("minor", ReleaseInfo.getBuildNumber() + "");
    pars.put("check_version", "true");
    pars.put("level", System.getProperty("dotcms_level"));
    if (System.getProperty("dotcms_license_serial") != null) {
        pars.put("license", System.getProperty("dotcms_license_serial"));
    }

    HttpClient client = new HttpClient();

    PostMethod method = new PostMethod(fileUrl);
    Object[] keys = (Object[]) pars.keySet().toArray();
    NameValuePair[] data = new NameValuePair[keys.length];
    for (int i = 0; i < keys.length; i++) {
        String key = (String) keys[i];
        NameValuePair pair = new NameValuePair(key, pars.get(key));
        data[i] = pair;
    }

    method.setRequestBody(data);
    String ret = null;

    try {
        client.executeMethod(method);
        int retCode = method.getStatusCode();
        if (retCode == 204) {
            Logger.info(UpdateUtil.class, "No new updates found");
        } else {
            if (retCode == 200) {
                String newMinor = method.getResponseHeader("Minor-Version").getValue();
                String newPrettyName = null;
                if (method.getResponseHeader("Pretty-Name") != null) {
                    newPrettyName = method.getResponseHeader("Pretty-Name").getValue();
                }

                if (newPrettyName == null) {
                    Logger.info(UpdateUtil.class, "New Version: " + newMinor);
                    ret = newMinor;
                } else {
                    Logger.info(UpdateUtil.class, "New Version: " + newPrettyName + "/" + newMinor);
                    ret = newPrettyName;
                }

            } else {
                throw new DotDataException(
                        "Unknown return code: " + method.getStatusCode() + " (" + method.getStatusText() + ")");
            }
        }
    } catch (HttpException e) {
        Logger.error(UpdateUtil.class, "HttpException: " + e.getMessage(), e);
        throw new DotDataException("HttpException: " + e.getMessage(), e);

    } catch (IOException e) {
        Logger.error(UpdateUtil.class, "IOException: " + e.getMessage(), e);
        throw new DotDataException("IOException: " + e.getMessage(), e);
    }

    return ret;
}