Example usage for org.apache.http.client.utils URLEncodedUtils format

List of usage examples for org.apache.http.client.utils URLEncodedUtils format

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils format.

Prototype

public static String format(final Iterable<? extends NameValuePair> parameters, final Charset charset) 

Source Link

Document

Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.

Usage

From source file:org.wso2.cep.ui.integration.test.login.DataSourcesTestCase.java

@Test(groups = "wso2.cep", description = "Verifying XSS Vulnerability in event data sources - driver field")
public void testXSSVenerabilityDriverField() throws Exception {
    boolean isVulnerable = false;

    // Login/*w  w  w  .j  av a  2  s . co m*/
    driver.get(getLoginURL());
    driver.findElement(By.id("txtUserName")).clear();
    driver.findElement(By.id("txtUserName"))
            .sendKeys(cepServer.getContextTenant().getContextUser().getUserName());
    driver.findElement(By.id("txtPassword")).clear();
    driver.findElement(By.id("txtPassword"))
            .sendKeys(cepServer.getContextTenant().getContextUser().getPassword());
    driver.findElement(By.cssSelector("input.button")).click();

    // Sending request to even-tracer admin service
    String url = backendURL.substring(0, 22) + "/carbon/ndatasource/validateconnection-ajaxprocessor.jsp?";
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("dsName", "John"));
    params.add(new BasicNameValuePair("driver", "<script>alert(1)</script>"));
    params.add(new BasicNameValuePair("url", "http://abc.com"));
    params.add(new BasicNameValuePair("username", "John"));
    params.add(new BasicNameValuePair("dsType", "RDBMS"));
    params.add(new BasicNameValuePair("dsProviderType", "default"));
    url += URLEncodedUtils.format(params, "UTF-8");

    driver.get(url);
    try {
        // Alert appears if vulnerable to XSS attack.
        Alert alert = driver.switchTo().alert();
        alert.accept();
        isVulnerable = true;
    } catch (NoAlertPresentException e) {
        // XSS vulnerability is not there
    }
    Assert.assertFalse(isVulnerable);
    driver.close();
}

From source file:dk.kasperbaago.JSONHandler.JSONHandler.java

public String getURL() {

    //Making a HTTP client
    HttpClient client = new DefaultHttpClient();

    //Declaring HTTP response
    HttpResponse response = null;/*  ww  w  . j  av  a2s . c  o m*/
    String myReturn = null;

    try {

        //Making a HTTP getRequest or post request
        if (method == "get") {
            String parms = "";
            if (this.parameters.size() > 0) {
                parms = "?";
                parms += URLEncodedUtils.format(this.parameters, "utf-8");
            }

            Log.i("parm", parms);
            Log.i("URL", this.url + parms);
            HttpGet getUrl = new HttpGet(this.url + parms);

            //Executing the request
            response = client.execute(getUrl);
        } else if (method == "post") {
            HttpPost getUrl = new HttpPost(this.url);

            //Sets parameters to add
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (int i = 0; i < this.parameters.size(); i++) {
                if (this.parameters.get(i).getName().equalsIgnoreCase(fileField)) {
                    entity.addPart(parameters.get(i).getName(),
                            new FileBody(new File(parameters.get(i).getValue())));
                } else {
                    entity.addPart(parameters.get(i).getName(), new StringBody(parameters.get(i).getName()));
                }
            }

            getUrl.setEntity(entity);

            //Executing the request
            response = client.execute(getUrl);
        } else {
            return "false";
        }

        //Returns the data      
        HttpEntity content = response.getEntity();
        InputStream mainContent = content.getContent();
        myReturn = this.convertToString(mainContent);
        this.HTML = myReturn;
        Log.i("Result", myReturn);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return myReturn;
}

From source file:co.tuzza.clicksend4j.client.ClickSendSmsClient.java

public SmsResults sendSms(SMS sms) throws Exception {
    List<NameValuePair> params = parseSMS(sms);
    String response = null;/*w  w w  .  j a v a2s  .  c o  m*/
    for (int pass = 1; pass <= 3; pass++) {
        HttpUriRequest method;
        HttpPost httpPost = new HttpPost(baseUrl + Definitions.SEND_SMS_URL_JSON);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        httpPost.setHeader("Authorization", "Basic " + this.authHeader);
        method = httpPost;
        String url = baseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
        try {
            if (httpClient == null) {
                httpClient = HttpClientUtils.getInstance(connectionTimeout, socketTimeout).getHttpClient();
            }
            HttpResponse httpResponse = httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200) {
                if (status == 401) {
                    throw new Exception("got a 401 response from ClickSend-HTTP for url [ " + url
                            + " ] - Authorisation failed");
                }
                throw new Exception("got a non-200 response [ " + status + " ] from ClickSend-HTTP for url [ "
                        + url + " ] ");
            }
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info("SMS SEND CLICKSEND-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception ex) {
            method.abort();
            log.info("communication failure", ex);
            String exceptionMsg = ex.getMessage();
            if (exceptionMsg.contains("Read timed out")) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass < 2) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }
            SmsResults results = new SmsResults();
            SmsResult smsResult = new SmsResult();

            smsResult.setResult("LOCAL500");
            smsResult.setErrorText("Failed to communicate with CLICKSEND-HTTP url [ " + url + " ] ..." + ex);
            smsResult.setStatusDescription(Definitions.SEND_SMS_RESPONSE_CODES_MAP.get("LOCAL500"));

            results.addSmsResult(smsResult);
            return results;
        }
    }

    JsonParser jsonParser = new JsonParser();
    SmsResults smsResults = jsonParser.parseJson(response, SmsResults.class);

    return smsResults;
}

From source file:org.cloudsmith.geppetto.forge.client.ForgeHttpClient.java

private HttpGet createGetRequest(String urlStr, Map<String, String> params, boolean useV1) {
    StringBuilder bld = new StringBuilder(useV1 ? createV1Uri(urlStr) : createV2Uri(urlStr));
    if (params != null && !params.isEmpty()) {
        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, String> param : params.entrySet())
            pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
        bld.append('?');
        bld.append(URLEncodedUtils.format(pairs, UTF_8.name()));
    }/*from  w w  w . j a v a 2  s .c  om*/
    return new HttpGet(URI.create(bld.toString()));
}

From source file:de.topicmapslab.couchtm.internal.utils.SysDB.java

/**
 * Sends a GET request to the database.//from   w w w .  j  a v a 2  s  . c o  m
 * 
 * @param query
 * @param key
 * @param db database name
 * @return result string
 */
protected String getMethod(String query, String key, String db) {
    String responseBody = "{}";
    URI uri = null;
    if (key != null) {
        List<NameValuePair> pair = new ArrayList<NameValuePair>();
        pair.add(new BasicNameValuePair("key", key));
        key = URLEncodedUtils.format(pair, "UTF-8");
    }
    try {
        uri = URIUtils.createURI("http", url, port, db + "/" + query, key, null);
        //System.out.println("get: "+uri.toString());
        get = new HttpGet(uri);
        responseBody = client.execute(get, responseHandler);
    } catch (HttpResponseException e) {
        //System.out.println("status Code: "+e.getStatusCode());
        //System.out.println("URI: "+uri.toString());
        //System.out.println("query: "+query+" key: "+key+" db: "+db);
    } catch (Exception e) {
        //System.err.println(uri.toString());
        e.printStackTrace();
    }
    return responseBody;
}

From source file:com.bricolsoftconsulting.geocoderplus.Geocoder.java

private String getGeocodingUrl(String locationName) {
    // Declare/*from w w  w . j a  v  a2 s. c o m*/
    String url;
    Vector<BasicNameValuePair> params;

    // Extract language from locale
    String language = mLocale.getLanguage();

    // Create params
    params = new Vector<BasicNameValuePair>();
    params.add(new BasicNameValuePair(PARAM_SENSOR, "true"));
    params.add(new BasicNameValuePair(PARAM_ADDRESS, locationName));
    if (language != null && language.length() > 0) {
        params.add(new BasicNameValuePair(PARAM_LANGUAGE, language));
    }
    if (mUseRegionBias) {
        String region = mLocale.getCountry();
        params.add(new BasicNameValuePair(PARAM_REGION, region));
    }

    // Create URL
    String encodedParams = URLEncodedUtils.format(params, "UTF-8");
    url = URL_MAPS_GEOCODE + "?" + encodedParams;

    // Return
    return url;
}

From source file:edu.mit.mobile.android.demomode.Preferences.java

private String toConfigString() {

    final String password = mPrefs.getString(KEY_PASSWORD, null);

    final ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();

    int ver;/*w  w  w .  j  a  v a 2s.  c om*/
    try {
        ver = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

    } catch (final NameNotFoundException e) {
        // this should never happen
        ver = 0;
        e.printStackTrace();
    }
    nvp.add(new BasicNameValuePair(CFG_K_VER, String.valueOf(ver)));
    nvp.add(new BasicNameValuePair(CFG_K_SECRETKEY, password));
    final Cursor c = getContentResolver().query(LauncherItem.CONTENT_URI, null, null, null, null);

    try {
        final int pkgCol = c.getColumnIndex(LauncherItem.PACKAGE_NAME);
        final int actCol = c.getColumnIndex(LauncherItem.ACTIVITY_NAME);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            nvp.add(new BasicNameValuePair(CFG_K_APPS,
                    c.getString(pkgCol) + CFG_PKG_SEP + c.getString(actCol)));
        }

        return "data:" + CFG_MIME_TYPE + "," + URLEncodedUtils.format(nvp, "utf-8");

    } finally {
        c.close();
    }

}

From source file:com.ab.http.AbRequestParams.java

/**
 * ??.
 * @return the param string
 */
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}

From source file:edu.scripps.fl.pubchem.web.session.PCWebSession.java

protected InputStream getAssayFile(String format, String ext, int aid) throws Exception {
    List<NameValuePair> params = addParameters(new ArrayList<NameValuePair>(), "aid", aid, "q", "r", "exptype",
            format, "zip", "gzip", "resultsummary", "detail", "releasehold", "t");
    URI uri = URIUtils.createURI("http", SITE, 80, "/assay/assay.cgi", URLEncodedUtils.format(params, "UTF-8"),
            null);//from   w w  w  .j  a  va 2s  . c  om
    Document document = new WaitOnRequestId(uri).asDocument();
    return getFtpLinkAsStream(document);
}

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/*www  .j  a v a 2  s .  c  o  m*/
* @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;
}