Example usage for org.apache.commons.httpclient.protocol Protocol registerProtocol

List of usage examples for org.apache.commons.httpclient.protocol Protocol registerProtocol

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.protocol Protocol registerProtocol.

Prototype

public static void registerProtocol(String paramString, Protocol paramProtocol) 

Source Link

Usage

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

public static void main(String[] args) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    String url = "https://pericles.symbiont.net/jccook";

    ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();
    Protocol https = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", https);

    HttpMethod method = new GetMethod(url);
    client.executeMethod(method);//w w w  .java2 s .co m
    String response = method.getResponseBodyAsString();
    System.out.println(response);
    method.releaseConnection();
    method.recycle();
}

From source file:httpsdemo.client.Client.java

public static void main(String args[]) throws Exception {

    File clientKeystore = new File("certs/clientKeystore.jks");
    File truststore = new File("certs/commonTruststore.jks");

    // Send HTTP GET request to query customer info - using portable HttpClient method
    Protocol authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(clientKeystore.toURI().toURL(),
            "password", truststore.toURI().toURL(), "password"), 9000);
    Protocol.registerProtocol("https", authhttps);

    System.out.println("Sending HTTPS GET request to query customer info");
    HttpClient httpclient = new HttpClient();
    GetMethod httpget = new GetMethod(BASE_SERVICE_URL + "/123");
    httpget.addRequestHeader("Accept", "text/xml");

    // If Basic Authentication required could use: 
    /*//from  w ww .j av a 2s .c o m
    String authorizationHeader = "Basic " 
       + org.apache.cxf.common.util.Base64Utility.encode("username:password".getBytes());
    httpget.addRequestHeader("Authorization", authorizationHeader);
    */
    try {
        httpclient.executeMethod(httpget);
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        httpget.releaseConnection();
    }

    /*
     *  Send HTTP PUT request to update customer info, using CXF WebClient method
     *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("Sending HTTPS PUT to update customer name");
    WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
    Customer customer = new Customer();
    customer.setId(123);
    customer.setName("Mary");
    Response resp = wc.put(customer);

    /*
     *  Send HTTP POST request to add customer, using JAXRSClientProxy
     *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("\n");
    System.out.println("Sending HTTPS POST request to add customer");
    CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class,
            CLIENT_CONFIG_FILE);
    customer = new Customer();
    customer.setName("Jack");
    resp = wc.post(customer);

    System.out.println("\n");
    System.exit(0);
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {//from   w ww  .  j a  v a2s  . c o  m
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}

From source file:ExampleP2PHttpClient.java

public static void main(String[] args) {
    // initialize JXTA
    try {//from  w ww .j a v a 2 s.  c  o  m
        // 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:edu.isi.misd.tagfiler.security.TagFilerSecurity.java

/**
 * Loads any security settings into the current environment.
 *///from w  w  w  .  ja  v a2  s.c o m
@SuppressWarnings("deprecation")
public static void loadSecuritySettings() {

    // Read whether or not to allow self-signed certificates to be
    // authenticated,
    // if so then load a custom socket factory that allows them to be
    // trusted
    if (Boolean.valueOf(TagFilerProperties.getProperty("tagfiler.security.AllowSelfSignedCerts"))) {
        Protocol https = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", https);
    }
}

From source file:eu.eco2clouds.accounting.http.HCClientFactory.java

public static HttpClient getHttpClient() {
    try {//from  w w  w  .j  a  va  2s. c o  m
        Protocol authhttps = new Protocol("https",
                new AuthSSLProtocolSocketFactory(new URL("file:" + Configuration.keystore),
                        Configuration.keystoreKey, new URL("file:" + Configuration.keystore),
                        Configuration.keystoreKey),
                443);
        Protocol.registerProtocol("https", authhttps);
    } catch (MalformedURLException e) {
        logger.info("Wrong path for keystore file: " + e);
    }
    return new HttpClient();
}

From source file:com.utest.domain.service.util.TrustedSSLUtil.java

public static void initialize() {
    Protocol.registerProtocol("https", new Protocol("https", new TrustedSSLUtil(), 443));
}

From source file:net.heartsome.license.webservice.ServiceUtilTest.java

public static IService getService() throws MalformedURLException {
    // Service srvcModel = new
    // ObjectServiceFactory().create(IService.class);
    // XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
    // .newInstance().getXFire());
    ///*from   w w w .j a va2  s  .  c o m*/
    // IService srvc = (IService) factory.create(srvcModel,
    // Constants.CONNECT_URL);
    // return srvc;

    ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
    Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
    Protocol.registerProtocol(HTTP_TYPE, protocol);
    Service serviceModel = new ObjectServiceFactory().create(IService.class, SERVICE_NAME, SERVICE_NAMESPACE,
            null);

    IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
    Client client = ((XFireProxy) Proxy.getInvocationHandler(service)).getClient();
    client.addOutHandler(new DOMOutHandler());
    client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
    client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
    client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");

    return service;
}

From source file:net.heartsome.license.webservice.ServiceUtil.java

public static IService getService() throws MalformedURLException {
    //      Service srvcModel = new ObjectServiceFactory().create(IService.class);
    //      XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
    //            .newInstance().getXFire());
    ///*  w  w  w .j  a v  a2 s .co m*/
    //      IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
    //      return srvc;

    ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
    Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
    Protocol.registerProtocol(HTTP_TYPE, protocol);
    Service serviceModel = new ObjectServiceFactory().create(IService.class, SERVICE_NAME, SERVICE_NAMESPACE,
            null);

    IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
    Client client = ((XFireProxy) Proxy.getInvocationHandler(service)).getClient();
    client.addOutHandler(new DOMOutHandler());
    client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
    client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
    client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");

    return service;
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.support.UntrustedSSLProtocolSocketFactory.java

public static void register() {
    // don't croak on self-signed certs

    if (!isRegistered()) {
        if (untrustSSL == null) {
            ProtocolSocketFactory factory = (ProtocolSocketFactory) new UntrustedSSLProtocolSocketFactory();
            untrustSSL = new Protocol("https", factory, 443);
        }// ww  w  . j  a va 2s  .  c  om
        Protocol.registerProtocol("https", untrustSSL);
    }
}