Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider.

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ////  www .j a va2s.com
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();
}

From source file:no.norrs.projects.andronary.utils.HttpUtil.java

public static HttpResponse GET(URL url, UsernamePasswordCredentials creds)
        throws IOException, URISyntaxException {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);

    HttpGet httpGet = new HttpGet(url.toURI());

    httpGet.addHeader("Accept", "application/json");
    httpGet.addHeader("User-Agent", "Andronary/0.1");
    HttpResponse response;//from ww w  . j  a  va2s. com

    return httpClient.execute(httpGet);
}

From source file:no.norrs.projects.andronary.service.utils.HttpUtil.java

public static HttpResponse GET(URL url, UsernamePasswordCredentials creds)
        throws IOException, URISyntaxException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);

    HttpGet httpGet = new HttpGet(url.toURI());

    httpGet.addHeader("Accept", "application/json");
    httpGet.addHeader("User-Agent", "Andronary/0.1");
    HttpResponse response;/*from ww  w . j  a  v  a2 s.c o  m*/

    return httpClient.execute(httpGet);
}

From source file:com.marklogic.client.functionaltest.JavaApiBatchSuite.java

public static void deleteRESTAppServerWithDB(String restServerName) {
    try {//from w  w  w . j  a  va  2  s.  c om
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));

        HttpDelete delete = new HttpDelete(
                "http://localhost:8002/v1/rest-apis/" + restServerName + "?include=content&include=modules");

        HttpResponse response = client.execute(delete);
        if (response.getStatusLine().getStatusCode() == 202) {
            Thread.sleep(3500);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:com.marklogic.client.functionaltest.JavaApiBatchSuite.java

public static void createRESTAppServer(String restServerName, int restPort) {
    try {//from w  w  w .  j av  a2s  .  co  m
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpPost post = new HttpPost("http://localhost:8002" + "/v1/rest-apis?format=json");
        String JSONString = "{ \"rest-api\": {\"name\":\"" + restServerName + "\",\"port\":\"" + restPort
                + "\"}}";
        //System.out.println(JSONString);      
        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(JSONString));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:com.marklogic.client.functionaltest.JavaApiBatchSuite.java

public static void createRESTUser(String usrName, String pass, String roleName) {
    try {/* w w w  .  j  a  va2s  . c o m*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/users?format=json");
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode mainNode = mapper.createObjectNode();
        //         ObjectNode childNode = mapper.createObjectNode();
        ArrayNode childArray = mapper.createArrayNode();
        mainNode.put("name", usrName);
        mainNode.put("description", "user discription");
        mainNode.put("password", pass);
        childArray.add(roleName);
        mainNode.put("role", childArray);
        //System.out.println(type + mainNode.path("range-element-indexes").path("range-element-index").toString());
        //            System.out.println(mainNode.toString());
        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(mainNode.toString()));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 400) {
            System.out.println("User already exist or a bad create request");
        } else if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        } else {
            System.out.print("No Proper Response");
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:be.benvd.mvforandroid.data.MVDataHelper.java

/**
 * Returns the GET response of the given url.
 * /*from ww  w .  ja va 2s.  c  om*/
 * @throws IOException
 * @return The response of the given URL. If no response was found, null is
 *         returned.
 */
public static String getResponse(String username, String password, String url) throws IOException {
    /*      DefaultHttpClient httpclient = new DefaultHttpClient();
          httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username + ":" + password));
          HttpGet httpget = new HttpGet(url);
          HttpResponse response = httpclient.execute(httpget);
    */
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials creds = new UsernamePasswordCredentials(username, password);
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);

    String auth = android.util.Base64.encodeToString((username + ":" + password).getBytes("UTF-8"),
            android.util.Base64.NO_WRAP);

    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("Authorization", "Basic " + auth);
    HttpResponse response = httpclient.execute(httpget);

    if (response.getEntity() != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        Log.v(MVDataHelper.class.getSimpleName(), "Response:" + sb.toString());
        return sb.toString();
    }

    return null;
}

From source file:de.fmaul.android.cmis.utils.HttpUtils.java

private static HttpClient createClient(String user, String password) {
    DefaultHttpClient client = new DefaultHttpClient();

    if (user != null && user.length() > 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
    }/*w w w. ja va  2 s.  com*/

    return client;
}

From source file:org.hibernate.ogm.datastore.couchdb.test.dialect.authenticated.AuthenticatedAccessTest.java

private static ResteasyClient getClientWithServerAdminCredentials() {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(serverAdminUser, serverAdminPassword));

    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost(host, port, "http"), new BasicScheme());

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    return new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(httpClient, localContext))
            .build();// w w  w. java 2s .  c  om
}

From source file:com.amalto.workbench.utils.ResourcesUtil.java

private static void postContent(String uri, HttpPost httppost) throws Exception, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(getEndpointHost(uri), Integer.valueOf(getEndpointPort(uri))),
            new UsernamePasswordCredentials("admin", "talend"));//$NON-NLS-1$//$NON-NLS-2$

    log.info(Messages.ResourcesUtil_Loginfo + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    try {//from   w  w w  .j  a  v  a 2  s .  c o m
        Header[] headers = response.getAllHeaders();
        String responseString = null;
        if (response.getEntity() != null) {
            responseString = EntityUtils.toString(response.getEntity());
        }
    } finally {
        if (entity != null) {
            entity.consumeContent(); // release connection gracefully
        }
    }
    if (entity != null) {
        entity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
}