Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials.

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:Main.java

public static void PostRequest(String url, Map<String, String> params, String userName, String password,
        Handler messageHandler) {
    HttpPost postMethod = new HttpPost(url);
    List<NameValuePair> nvps = null;
    DefaultHttpClient client = new DefaultHttpClient();

    if ((userName != null) && (userName.length() > 0) && (password != null) && (password.length() > 0)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
    }/*from  ww w  . j a v  a  2s. c  o m*/

    final Map<String, String> sendHeaders = new HashMap<String, String>();
    sendHeaders.put(CONTENT_TYPE, MIME_FORM_ENCODED);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            for (String key : sendHeaders.keySet()) {
                if (!request.containsHeader(key)) {
                    request.addHeader(key, sendHeaders.get(key));
                }
            }
        }
    });

    if ((params != null) && (params.size() > 0)) {
        nvps = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
    }
    if (nvps != null) {
        try {
            postMethod.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    ExecutePostRequest(client, postMethod, GetResponseHandlerInstance(messageHandler));
}

From source file:com.zhch.example.commons.http.v4_5.ProxyTunnelDemo.java

/**
 * ?? demo/*  ww w  . ja va2 s  .c  o  m*/
 * 
 * @throws Exception
 */
public final static void officalDemo() throws Exception {
    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.yahoo.com", 80);
    HttpHost proxy = new HttpHost("localhost", 8888);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:com.ibm.watson.retrieveandrank.app.rest.UtilityFunctions.java

public static CloseableHttpClient createHTTPClient(URI uri, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));
    return HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor()).build();
}

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);
    }//from   ww  w  . ja  v a2 s  .  c o  m

    return client;
}

From source file:justdailscrapper.vik.utility.FetchPageWithoutProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl, List<ProxyImport> proxyList)
        throws IOException, InterruptedException {

    Random r = new Random();

    ProxyImport obj = proxyList.get(r.nextInt(proxyList.size()));

    String ip = obj.proxyIP;/*  w  ww  . j  ava2 s  .c  om*/
    int portno = Integer.parseInt(obj.proxyPort);
    String username = "";
    String password = "";
    if (obj.proxyLen > 2) {
        username = obj.proxyUserName;
        password = obj.proxyPassword;
    }

    //        int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope(ip, portno),
            new UsernamePasswordCredentials(username, password));
    HttpHost proxy = new HttpHost(ip, portno);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Host", "www.justdial.com");
        httpget.addHeader("Referer", "https://www.justdial.com/Bangalore/Yamaha-Two-Wheeler-Dealers");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Requested-With", "XMLHttpReques");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:io.fabric8.maven.support.Apps.java

/**
 * Posts a file to the git repository//ww  w . jav a2s.  c o m
 */
public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl,
        String branch, String path, Logger logger) throws URISyntaxException, IOException {
    HttpClientBuilder builder = HttpClients.custom();
    if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443),
                new UsernamePasswordCredentials(user, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }

    CloseableHttpClient client = builder.build();
    try {

        String url = consoleUrl;
        if (!url.endsWith("/")) {
            url += "/";
        }
        url += "git/";
        url += branch;
        if (!path.startsWith("/")) {
            url += "/";
        }
        url += path;

        logger.info("Posting App Zip " + file.getName() + " to " + url);
        URI buildUrl = new URI(url);
        HttpPost post = new HttpPost(buildUrl);

        // use multi part entity format
        FileBody zip = new FileBody(file);
        HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build();
        post.setEntity(entity);
        // post.setEntity(new FileEntity(file));

        HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post);
        logger.info("Response: " + response);
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 200 || statusCode >= 300) {
                throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response);
            }
        }
        return response;
    } finally {
        Closeables.closeQuietly(client);
    }
}

From source file:org.eclipse.epp.internal.mpc.core.util.HttpUtil.java

public static void configureProxy(HttpClient client, String url) {
    final IProxyData proxyData = ProxyHelper.getProxyData(url);
    if (proxyData != null && !IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) {
        HttpHost proxy = new HttpHost(proxyData.getHost(), proxyData.getPort(),
                proxyData.getType().toLowerCase());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (proxyData.isRequiresAuthentication()) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyData.getHost(), proxyData.getPort()),
                    new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword()));
        }//ww  w. ja v a  2s  .c  om
    }
}

From source file:justdailscrapper.vik.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl, List<ProxyImport> proxyList)
        throws IOException, InterruptedException {

    Random r = new Random();

    ProxyImport obj = proxyList.get(r.nextInt(proxyList.size()));

    String ip = obj.proxyIP;/* w w  w  .j a v a2 s .  co  m*/
    int portno = Integer.parseInt(obj.proxyPort);
    String username = "";
    String password = "";
    if (obj.proxyLen > 2) {
        username = obj.proxyUserName;
        password = obj.proxyPassword;
    }

    //        int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope(ip, portno),
            new UsernamePasswordCredentials(username, password));
    HttpHost proxy = new HttpHost(ip, portno);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Host", "www.justdial.com");
        httpget.addHeader("Referer", "https://www.justdial.com/Bangalore/Yamaha-Two-Wheeler-Dealers");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Requested-With", "XMLHttpReques");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    logTextArea.append("PROX FAILURE\n");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                logTextArea.append("Response content length: " + entity.getContentLength() + "\n");
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:com.liferay.mobile.android.auth.basic.BasicAuthentication.java

@Override
public void authenticate(HttpRequest request) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    Header header = BasicScheme.authenticate(credentials, "UTF-8", false);
    request.addHeader(header);/*from w  w  w .ja  va2  s  . c  o  m*/
}

From source file:com.infojobs.hereismyjob.httpmanager.HttpManager.java

public HttpManager(String str) {
    try {//w w  w.j  ava2  s .co  m
        client = new DefaultHttpClient();
        targetHost = new HttpHost(Constants.HOST_NAME, Constants.PORT_NUMBER, Constants.HOST_SCHEME);
        // Client credentials
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("Aladdin", "open sesame"));
        // create a GET method that queries some API operation  
        request = new HttpGet(str);
        // execute the operation  
        response = client.execute(targetHost, request);

        // print the status and the contents of the response  
        System.out.println(response.getStatusLine());
        System.out.println(EntityUtils.toString(response.getEntity()));

    } catch (MalformedURLException ex) {
        Constants.showException("Malformed URL exception: " + ex);
    } catch (IOException ex) {
        Constants.showException("Input/Output exception: " + ex);
    } finally {
        // release any connection resources used by the method  
        client.getConnectionManager().shutdown();
    }
}