Example usage for org.apache.http.impl.auth BasicScheme authenticate

List of usage examples for org.apache.http.impl.auth BasicScheme authenticate

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme authenticate.

Prototype

@Deprecated
public static Header authenticate(final Credentials credentials, final String charset, final boolean proxy) 

Source Link

Document

Returns a basic Authorization header value for the given Credentials and charset.

Usage

From source file:ua.kiev.doctorvera.utils.SMSGateway.java

@SuppressWarnings("deprecation")
public ArrayList<String> send(String phone, String sms) {
    ArrayList<String> result = new ArrayList<String>();
    final String MESSAGE = "<message><service id='single' source='" + FROM + "'/><to>" + phone
            + "</to><body content-type='text/plain'>" + sms + "</body></message>";

    @SuppressWarnings("resource")
    HttpClient httpclient = new DefaultHttpClient();
    String xml = null;//from   w  ww.j  a  v a  2s . c o m
    try {
        HttpPost httpPost = new HttpPost(SMS_SEND_URL);

        StringEntity entity = new StringEntity(MESSAGE, "UTF-8");
        entity.setContentType("text/xml");
        entity.setChunked(true);
        httpPost.setEntity(entity);
        httpPost.addHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(LOGIN, PASS), "UTF-8", false));
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        LOG.info("Sending SMS: " + (response.getStatusLine().getStatusCode() == 200));
        xml = EntityUtils.toString(resEntity);
    } catch (Exception e) {
        LOG.severe("" + e.getStackTrace());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    //parsing xml result
    Document doc = loadXMLFromString(xml);
    NodeList nl = doc.getElementsByTagName("status");
    Element status = (Element) nl.item(0);

    result.add(0, status.getAttribute("id").toString()); //tracking id at position 0
    result.add(1, status.getAttribute("date").toString()); //date at position 1
    result.add(2, getElementValue(status.getFirstChild())); //state at position 2
    return result;
}

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

/**
 * Returns HTTP GET response from given url using admin credentials
 *
 * @param url request url suffix//from  ww w  .  j  av a  2  s . c o m
 * @return
 * @throws IOException
 */
public static HttpResponse getRequestResponse(String url) throws IOException {

    String restUrl = getRestEndPoint(url);
    log.info("Sending HTTP GET request: " + restUrl);
    client = new DefaultHttpClient();
    request = new HttpGet(restUrl);

    request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("admin", "admin"),
            Charset.defaultCharset().toString(), false));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(request);
    return response;
}

From source file:org.que.async.AsyncGETRequester.java

@Override
protected List<JSONObject> doInBackground(GetRequestInfo... urls) {
    List<JSONObject> result = new ArrayList<JSONObject>();
    if (urls != null) {
        for (int i = 0; i < urls.length; i++) {
            String url = urls[i].getUrl();
            if (url != null) {
                HttpGet get = new HttpGet(url);
                String etag = urls[i].getEtag();
                if (etag != null && !etag.isEmpty()) {
                    get.setHeader(HEADER_IF_NONE_MATCH, etag);
                }/* w ww.  j ava2  s  .co m*/

                if (credentials != null) {
                    get.addHeader(BasicScheme.authenticate(credentials, HTTP.UTF_8, false));
                }
                executeGetRequest(get, result);
            }
        }
    }
    return result;
}

From source file:com.appdynamics.monitors.boundary.BoundaryWrapper.java

/**
 * Retrieves observation domain ids from the /meters REST request
 * @return  Map       A map containing the name of the meter and it's corresponding observationDomainId
 *///from w ww  .j  a v a 2 s .  c  o m
private void populateObservationDomainIds() throws Exception {
    HttpGet httpGet = new HttpGet(constructMetersURL());
    httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(apiKey, ""), "UTF-8", false));

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder responseString = new StringBuilder();
    String line = "";
    while ((line = bufferedReader2.readLine()) != null) {
        responseString.append(line);
    }

    JsonArray responseArray = new JsonParser().parse(responseString.toString()).getAsJsonArray();

    for (int i = 0; i < responseArray.size(); i++) {
        JsonObject obj = responseArray.get(i).getAsJsonObject();
        meterIds.put(obj.get("name").getAsString(), obj.get("obs_domain_id").getAsString());
    }
}

From source file:uk.org.openeyes.APIUtils.java

/**
 * Trigger a WS call through HTTP for patient search
 * //from  w w w .  j  a  v  a 2  s  . c  o m
 * @param resourceType The REST resource name (only "Patient" supported now)
 * @param requestParams The arguments for the HTTP call 
 * @return The status code from the HTTP answer
 * @throws ConnectException 
 */
public int read(String resourceType, String requestParams) throws ConnectException {

    DefaultHttpClient http = new DefaultHttpClient();

    int result = -1;
    String strURL = "http://" + host + ":" + port + "/api/" + resourceType
            + "?resource_type=Patient&_format=xml";
    if (requestParams != null) {
        strURL += "&" + requestParams;
    }
    HttpGet get = new HttpGet(strURL);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(authUserName, authUserPassword);

    get.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));

    try {
        get.addHeader("Content-type", "text/xml");
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient httpclient = builder.build();

        CloseableHttpResponse httpResponse = httpclient.execute(get);
        result = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity2 = httpResponse.getEntity();
        StringWriter writer = new StringWriter();
        //IOUtils.copy(entity2.getContent(), writer);
        this.response = entity2.getContent().toString();
        EntityUtils.consume(entity2);
    } catch (ConnectException e) {
        // this happens when there's no server to connect to
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();
    }
    return result;
}

From source file:com.serena.rlc.provider.servicenow.client.ApprovalWaiter.java

synchronized void notifyRLC(String status) {
    try {/*from  www .  j a v  a 2 s . co  m*/
        String uri = callbackUrl + executionId + "/" + status;
        logger.debug("Start executing RLC PUT request to url=\"{}\"", uri);
        DefaultHttpClient rlcParams = new DefaultHttpClient();
        HttpPut put = new HttpPut(uri);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(callbackUsername,
                callbackPassword);
        put.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
        //put.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //put.addHeader("Accept", "application/json");
        logger.info(credentials.toString());
        HttpResponse response = rlcParams.execute(put);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.error("HTTP Status Code: " + response.getStatusLine().getStatusCode());
        }
    } catch (IOException ex) {
        logger.error(ex.getLocalizedMessage());
    }
}

From source file:com.serena.rlc.provider.jenkins.client.JenkinsClient.java

/**
 * Send a POST and returns the Location header which contains the url to the queued item
 *
 * @param jenkinsUrl/*from w ww .  j  av a 2  s .c o  m*/
 * @param postPath
 * @param postData
 * @return Response body
 * @throws JenkinsClientException
 */
public String processBuildPost(String jenkinsUrl, String postPath, String postData)
        throws JenkinsClientException {
    String uri = createUrl(jenkinsUrl, postPath);

    logger.debug("Start executing Jenkins POST request to url=\"{}\" with payload={}", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(uri);

    if (getJenkinsUsername() != null && !StringUtils.isEmpty(getJenkinsUsername())) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJenkinsUsername(),
                getJenkinsPassword());
        postRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    }

    postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    postRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
    String result = "";

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("json", postData));

    try {

        postRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw createHttpError(response);
        }

        result = response.getFirstHeader("Location").getValue();

        logger.debug("End executing Jenkins POST request to url=\"{}\" and receive this result={}", uri,
                result);

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new JenkinsClientException("Server not available", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:com.iia.giveastick.util.RestClient.java

public String invoke(Verb verb, String path, JSONObject jsonParams, List<Header> headers) throws Exception {
    //EncodingTypes charset=serviceContext.getCharset();
    long startTime = 0, endTime = 0;
    String result = null;//from w ww  .  j  a v a 2 s . c om
    this.statusCode = 404;

    HttpResponse response = null;
    HttpHost targetHost = new HttpHost(this.serviceName, this.port, this.scheme);

    //HttpEntity entity = this.buildMultipartEntity(params);
    HttpEntity entity = null;

    if (jsonParams != null && jsonParams.has("file")) {
        entity = this.buildMultipartEntity(jsonParams);
    } else {
        entity = this.buildJsonEntity(jsonParams);
    }

    HttpRequest request = this.buildHttpRequest(verb, path, entity, headers);

    if (this.login != null && this.password != null) {
        request.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(this.login, this.password),
                "UTF-8", false));
    }

    if (!TextUtils.isEmpty(this.CSRFtoken)) {
        request.addHeader("X-CSRF-Token", this.CSRFtoken);
    }

    try {
        if (debugWeb) {
            startTime = System.currentTimeMillis();
        }

        response = this.httpClient.execute(targetHost, request);
        this.statusCode = response.getStatusLine().getStatusCode();

        this.readHeader(response);

        if (debugWeb) {
            endTime = System.currentTimeMillis();
        }

        // we assume that the response body contains the error message
        HttpEntity resultEntity = response.getEntity();

        if (resultEntity != null) {
            result = EntityUtils.toString(resultEntity, HTTP.UTF_8);
        }

        if (debugWeb && GiveastickApplication.DEBUG) {
            final long endTime2 = System.currentTimeMillis();

            //System.out.println(
            //   "The REST response is:\n " + serviceResponse);
            Log.d(TAG, "Time taken in REST operation : " + (endTime - startTime) + " ms. => [" + verb + "]"
                    + path);
            Log.d(TAG, "Time taken in service response construction : " + (endTime2 - endTime) + " ms.");
        }

    } catch (ConnectTimeoutException e) {
        Log.e(TAG, "Connection timed out. The host may be unreachable.");
        e.printStackTrace();

        throw new Exception(e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getCause().getMessage());

        throw new Exception(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();

        throw e;
    } finally {
        this.httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:com.ibm.watson.developer_cloud.android.text_to_speech.v1.TTSUtility.java

/**
* Post text data to the server and get returned audio data
* @param server iTrans server/* w w  w . j a  v  a2s .  c  om*/
* @param username
* @param password
* @param content
* @return {@link HttpResponse}
* @throws Exception
*/
public static HttpResponse createPost(String server, String username, String password, String token,
        boolean learningOptOut, String content, String voice, String codec) throws Exception {
    String url = server;

    //HTTP GET Client
    HttpClient httpClient = new DefaultHttpClient();
    //Add params
    List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("text", content));
    params.add(new BasicNameValuePair("voice", voice));
    params.add(new BasicNameValuePair("accept", codec));
    HttpGet httpGet = new HttpGet(url + "?" + URLEncodedUtils.format(params, "utf-8"));
    // use token based authentication if possible, otherwise Basic Authentication will be used
    if (token != null) {
        Log.d(TAG, "using token based authentication");
        httpGet.setHeader("X-Watson-Authorization-Token", token);
    } else {
        Log.d(TAG, "using basic authentication");
        httpGet.setHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));
    }

    if (learningOptOut) {
        Log.d(TAG, "setting X-Watson-Learning-OptOut");
        httpGet.setHeader("X-Watson-Learning-Opt-Out", "true");
    }
    HttpResponse executed = httpClient.execute(httpGet);
    return executed;
}