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

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

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Print this HttpException and its stack trace to the standard error stream.

Usage

From source file:com.chiral.oauth.OAuthLoginUtil.java

public static void main(String[] args) throws Exception {
    // Step 0: Connect to SalesForce.
    OAuthConfiguration config;//www .j av a2s  .  com
    File configFile = new File(args[0]);
    config = OAuthConfiguration.fromYaml(new FileInputStream(configFile));
    System.out.println("Getting a token");
    String tokenUrl = config.environment + "/services/oauth2/token";
    //TODO hparry use JAX-RS instead of Apache commons
    HttpClient httpclient = new HttpClient();
    PostMethod post = new PostMethod(tokenUrl);
    post.addParameter("grant_type", "password");
    post.addParameter("client_id", config.clientId);
    post.addParameter("client_secret", config.secret);
    post.addParameter("redirect_uri", config.redirectUri);
    post.addParameter("username", config.username);
    post.addParameter("password", config.password);

    try {
        httpclient.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        post.releaseConnection();
    }
}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUninstallCapabilityOnEdgeAcs.java

/**
 * @param args/*from w  w  w . j  a va2 s .  co m*/
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUninstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUninstall\""));

    // UUID: string
    // Version: string
    // ExecutionEnvRef: String

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "2.2.0");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUpdateCapabilityOnEdgeAcs.java

/**
 * @param args/*from  ww w.  j av a 2 s. c o  m*/
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUpdate
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUpdate\""));

    // UUID: string
    // Version: string
    // URL: string
    // Username: string
    // Password: string

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "1.0.0");
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-2.2.0.jar");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient/*from   w  w  w.ja v a2s. c o  m*/
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateInstallCapabilityOnEdgeAcs.java

/**
 * @param args/*from w  w w . j  a v  a  2  s .c  om*/
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateInstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateInstall\""));

    // URL: string
    // UUID: string
    // Username: string
    // Password: string
    // ExecutionEnvRef: string

    JSONObject object = new JSONObject();
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-1.0.0.jar");
    // object.put("UUID", "UUID_value");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);

        // 10 avr. 2013 10:09:23
        // org.apache.commons.httpclient.auth.AuthChallengeProcessor
        // selectAuthScheme
        // INFO: basic authentication scheme selected
        // status: 200
        // resp: "executed: changeDUStateInstall: {Password=Password_value,
        // Username=Username_value, ExecutionEnvRef=ExecutionEnvRef_value,
        // URL=http:\/\/archive.apache.org\/dist\/felix\/org.apache.felix.http.jetty-1.0.0.jar},
        // resp: com.netopia.nbbs.tr69.msg.ChangeDUStateResponse@2db81edf"

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

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

public static void main(String[] args) {

    // test();//ww w .  j a  v a  2 s.  c om
    // 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:cn.vlabs.duckling.common.http.WebSite.java

public static String getBodyContent(String url) {
    int index = url.indexOf("?");
    String query = "";
    if (index > 0) {
        query = url.substring(index + 1, url.length());
        url = url.substring(0, index);//from www .  j  a v  a 2  s  . co m
    }
    WebSite site = new WebSite(url);
    if (query.trim().length() > 0) {
        PostMethod method = site.createPostMethod(null);
        Map<String, String> params = extractParams(query.trim());
        for (String key : params.keySet()) {
            method.addParameter(key, params.get(key));
        }
        try {
            int code = site.exec(method);
            if (code == 200) {
                return method.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
            site.close();
        }
    } else {
        GetMethod method = site.createGetMethod("");
        try {
            int code = site.exec(method);
            if (code == 200) {
                return method.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
            site.close();
        }
    }
    return null;
}

From source file:com.alta189.cyborg.commit.ShortUrlService.java

public static String shorten(String url, String keyword) {
    switch (service) {
    case BIT_LY://from  w ww. ja  v a  2 s  . c  om
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
        method.setQueryString(
                new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"),
                        new NameValuePair("login", user), new NameValuePair("apiKey", apiKey),
                        new NameValuePair("format", "xml"), new NameValuePair("history", "1") });
        try {
            httpclient.executeMethod(method);
            String responseXml = method.getResponseBodyAsString();
            String retVal = null;
            if (responseXml != null) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                StringReader st = new StringReader(responseXml);
                Document d = db.parse(new InputSource(st));
                NodeList nl = d.getElementsByTagName("shortUrl");
                if (nl != null) {
                    Node n = nl.item(0);
                    retVal = n.getTextContent();
                }
            }

            return retVal;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return null;
    case SPOUT_IN:
        HttpClient client = new HttpClient();
        String result = null;
        client.getParams().setParameter("http.useragent", "Test Client");

        BufferedReader br = null;
        PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php");
        pMethod.addParameter("signature", apiKey);
        pMethod.addParameter("action", "shorturl");
        pMethod.addParameter("format", "simple");
        pMethod.addParameter("url", url);
        if (keyword != null) {
            pMethod.addParameter("keyword", keyword);
        }

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

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                pMethod.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream()));
                String readLine;
                if (((readLine = br.readLine()) != null)) {
                    result = readLine;
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            pMethod.releaseConnection();
            if (br != null) {
                try {
                    br.close();
                } catch (Exception fe) {
                    fe.printStackTrace();
                }
            }
        }
        return result;
    }
    return null;
}

From source file:com.prashsoft.javakiva.KivaUtil.java

public static Object getBeanResponse(String urlSuffix, String urlMethod, String urlParams) {

    Object bean = null;//from w w w  . ja  v a2s.co m

    String url = createKivaAPIUrl(urlSuffix, urlMethod, urlParams);

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

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

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

        // Read the response body.

        InputStream is = method.getResponseBodyAsStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));

        String datastr = null;
        StringBuffer sb = new StringBuffer();

        String inputLine;

        while ((inputLine = in.readLine()) != null)
            sb.append(inputLine);

        in.close();
        is.close();

        String response = sb.toString();

        // Deal with the response.
        JSONObject jsonObject = JSONObject.fromObject(response);

        bean = JSONObject.toBean(jsonObject);

    } 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();
    } catch (Exception e) {
        System.err.println("Fatal general error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return bean;

}

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

public static Cookie[] validateFromCAS2(String username, String password) throws Exception {

    String url = casServerUrlPrefix + "/v1/tickets?";

    String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and
    // re-created, using a persistence mechanism of choice,
    // Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient();

    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443);

    URI uri = new URI(url + s, true);
    // use relative url only
    PostMethod httpget = new PostMethod(url);
    httpget.addParameter("username", username);
    httpget.addParameter("password", password);

    HostConfiguration hc = new HostConfiguration();
    hc.setHost("atoll-dev.cls.fr", 8443, easyhttps);
    // client.executeMethod(hc, httpget);

    client.setState(initialState);// w w w  .  j ava2s.c  o m

    // Create a method instance.
    System.out.println(url + s);

    GetMethod method = new GetMethod(url + s);
    // 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);
    Cookie[] cookies = null;

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

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

        for (Header header : method.getRequestHeaders()) {
            System.out.println(header.getName());
            System.out.println(header.getValue());
        }
        // 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));

        System.out.println("Response status code: " + statusCode);
        // Get all the cookies
        cookies = client.getState().getCookies();
        // Display the cookies
        System.out.println("Present cookies: ");
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(" - " + cookies[i].toExternalForm());
        }

        Assertion assertion = AssertionHolder.getAssertion();
        if (assertion == null) {
            System.out.println("<p>Assertion is null</p>");
        }

    } 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();
    }

    return cookies;

}