Example usage for java.net URLEncoder encode

List of usage examples for java.net URLEncoder encode

Introduction

In this page you can find the example usage for java.net URLEncoder encode.

Prototype

public static String encode(String s, Charset charset) 

Source Link

Document

Translates a string into application/x-www-form-urlencoded format using a specific java.nio.charset.Charset Charset .

Usage

From source file:eu.sisob.uma.NPL.Researchers.Freebase.Utils.java

public static JsonArray getResultsFromAPISearchCall(String query, String key, String params) {
    String service_url = "https://www.googleapis.com/freebase/v1/search";
    String url = "";
    JsonObject json_data = null;//from   w ww .  ja  v a 2s .c  om
    try {
        url = service_url + "?query=" + URLEncoder.encode(query, "UTF-8") + params + "&key=" + key + "&limit=1";

        json_data = doRESTCall(url);
    } catch (UnsupportedEncodingException ex) {
        ProjectLogger.LOGGER.error(ex.getMessage());
        json_data = null;
    } catch (IOException ex) {
        ProjectLogger.LOGGER.error(ex.getMessage());
        json_data = null;
    }

    JsonArray results = null;
    if (json_data != null) {
        results = (JsonArray) json_data.get("result");
    }

    return results;
}

From source file:org.mitre.account_chooser.AccountChooserController.java

/**
 * Return the URL w/ GET parameters/*from   ww  w .j  av  a2s  .com*/
 * 
 * @param baseURI
 *            A String containing the protocol, server address, path, and
 *            program as per "http://server/path/program"
 * @param queryStringFields
 *            A map where each key is the field name and the associated
 *            key's value is the field value used to populate the URL's
 *            query string
 * @return A String representing the URL in form of
 *         http://server/path/program?query_string from the messaged
 *         parameters.
 */
public static String buildURL(String baseURI, Map<String, String> queryStringFields) {

    StringBuilder URLBuilder = new StringBuilder(baseURI);

    char appendChar = '?';

    for (Map.Entry<String, String> param : queryStringFields.entrySet()) {
        try {
            URLBuilder.append(appendChar).append(param.getKey()).append('=')
                    .append(URLEncoder.encode(param.getValue(), "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            throw new IllegalStateException(uee);
        }
        appendChar = '&';
    }

    return URLBuilder.toString();
}

From source file:api.APICall.java

public String getUserFeatures(String targetURL, String sessionKey) {
    String api = "getuserfeatures";
    targetURL = targetURL + api;//from   ww w .ja v  a  2 s  .  co m
    String urlParameters;
    try {
        urlParameters = "session-key=" + URLEncoder.encode(sessionKey, enc);
        String response = executePost(targetURL, urlParameters);
        return response;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;

}

From source file:lapispaste.Main.java

private static void paster(Map<String, String> pastemap, StringBuffer pdata) {
    try {/* ww  w. jav a2  s.c  o  m*/
        URL url = new URL("http://paste.linux-sevenler.org/index.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // set connection 'writeable'
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // construct the data...
        String data;
        String pdataString = pdata.toString();
        data = URLEncoder.encode("language", "ISO-8859-9") + "="
                + URLEncoder.encode(pastemap.get("format"), "ISO-8859-9");
        data += "&" + URLEncoder.encode("source", "ISO-8859-9") + "="
                + URLEncoder.encode(pdataString, "ISO-8859-9");
        data += "&" + URLEncoder.encode("submit", "ISO-8859-9") + "="
                + URLEncoder.encode(" Kaydet ", "ISO-8859-9");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // get new url where the paste is
        conn.getInputStream();
        System.out.println(conn.getURL());
        conn.disconnect();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:eu.skillpro.ams.pscm.connector.amsservice.ui.SendExecutableSkillToServer.java

public static Report push(String id, String snippet, String seeID) throws IOException {
    String serviceName = "registerResourceExecutableSkill";

    StringBuilder parameters = new StringBuilder();

    if (id != null && !id.trim().isEmpty()) {
        parameters.append("?id=" + URLEncoder.encode(id, "UTF-8"));
    }//w  ww.j  a  va 2s .  c o m

    if (seeID != null && !seeID.trim().isEmpty()) {
        parameters.append("&seeID=" + URLEncoder.encode(seeID, "UTF-8"));
    }

    if (snippet != null && !snippet.trim().isEmpty()) {
        parameters.append("&amlDescription=" + URLEncoder.encode(snippet, "UTF-8"));
    }

    HttpGet request = new HttpGet(AMSServiceUtility.serviceAddress + serviceName + parameters.toString());
    System.out.println(request.getRequestLine() + " =====================================");
    request.setHeader("Content-type", "application/json");

    HttpClient client = HttpClientBuilder.create().build();
    ;
    HttpResponse response = client.execute(request);

    System.out.println("Response status: " + response.getStatusLine().getStatusCode());

    String resp = EntityUtils.toString(response.getEntity());
    Report result = JSONUtility.convertToObject(resp, Report.class);
    return result;
}

From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * //from   w w  w  .  j  a v  a2  s  .c o  m
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    if (LOGGING.DEBUG)
        Log.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    if (LOGGING.DEBUG)
        Log.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    int linecount = 0;
    while ((line = rd.readLine()) != null) {
        linecount++;
        if (linecount <= 2) {
            if (LOGGING.DEBUG)
                Log.d(LOG_TAG, line);
        }
    }
    rd.close();
}

From source file:com.googlecode.psiprobe.jsp.ParamToggleTag.java

public int doStartTag() throws JspException {
    boolean getSize = ServletRequestUtils.getBooleanParameter(pageContext.getRequest(), param, false);
    StringBuffer query = new StringBuffer();
    query.append(param).append("=").append(!getSize);
    String encoding = pageContext.getResponse().getCharacterEncoding();
    for (Enumeration en = pageContext.getRequest().getParameterNames(); en.hasMoreElements();) {
        String name = (String) en.nextElement();
        if (!param.equals(name)) {
            try {
                String value = ServletRequestUtils.getStringParameter(pageContext.getRequest(), name, "");
                String encodedValue = URLEncoder.encode(value, encoding);
                query.append("&").append(name).append("=").append(encodedValue);
            } catch (UnsupportedEncodingException e) {
                throw new JspException(e);
            }/*from www.jav a  2s . c om*/
        }
    }
    try {
        pageContext.getOut().print(query);
    } catch (IOException e) {
        logger.debug("Exception printing query string to JspWriter", e);
        throw new JspException(e);
    }
    return EVAL_BODY_INCLUDE;
}

From source file:com.orange.datavenue.client.common.ApiInvoker.java

public String escapeString(String str) {
    try {//from w w  w. j a va2  s .  c  om
        return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
    } catch (UnsupportedEncodingException e) {
        return str;
    }
}

From source file:com.codepine.api.testrail.internal.QueryParameterString.java

@JsonAnySetter
public void addQueryParameter(String key, String value) throws UnsupportedEncodingException {
    if (queryParamStringBuilder.length() > 0) {
        queryParamStringBuilder.append('&');
    }//from w w  w . jav a 2  s  .c o  m
    queryParamStringBuilder.append(URLEncoder.encode(key, "UTF-8")).append('=')
            .append(URLEncoder.encode(value, "UTF-8"));
}

From source file:api.location.BaiduPlaceAPI.java

private String createUrlString() throws UnsupportedEncodingException {
    String baseUrl = "http://api.map.baidu.com/place/v2/search?ak=2d33ba4d2ab64e03723feb96caa13c57";

    Map<String, String> params = new HashMap<>();
    params.put("query", URLEncoder.encode("", "UTF-8"));
    params.put("tag", URLEncoder.encode("?", "UTF-8"));
    params.put("region", URLEncoder.encode("?", "UTF-8"));
    params.put("output", "json");

    StringBuilder sb = new StringBuilder();
    for (String key : params.keySet()) {
        sb.append("&" + key + "=" + params.get(key));
    }/*from   w  ww . ja va2 s .c o  m*/

    return baseUrl + sb.toString();
}