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:cn.guoyukun.spring.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
        String displayName) throws IOException {
    File file = new File(filePath);

    if (StringUtils.isEmpty(displayName)) {
        displayName = file.getName();/*from w w w  . j  a va  2 s  .c o  m*/
    }

    if (!file.exists() || !file.canRead()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return;
    }

    String userAgent = request.getHeader("User-Agent");
    boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

    response.reset();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate, no-transform");
    response.setDateHeader("Expires", 0L);

    response.setContentType("application/x-download");
    response.setContentLength((int) file.length());

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    if (isIE) {
        displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
    } else {
        displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
    }
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java

/**
 * Client Get Authorization Code/*from  ww w  . j a va 2s.  co m*/
 * @param authorityServerUri
 * @param clientId
 * @param redirectUri Authorization-Server will redirect user's browser to this URI with authorization-code. 
 * (optional, null means to use client pre-configurated value, but if no this configuration existed or 
 * have more than one configuration existing then must provide this parameter.)
 * @param scope Resource scope (optional, null means to default scope)
 * @param state Used to avoid cross-site request forgery (optional, can be null)
 * @return An URI which to let user's browser navigate to authorization server to obtain authority-code
 * @throws UnsupportedEncodingException 
 */
public static String makeAuthorizationUri(String authorityServerUri, String clientId, String redirectUri,
        String scope, String state) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder(authorityServerUri);
    if (authorityServerUri.contains("?"))
        result.append("&response_type=code");
    else
        result.append("?response_type=code");
    result.append("&client_id=").append(URLEncoder.encode(clientId, "utf-8"));
    if (redirectUri != null)
        result.append("&redirect_uri=").append(URLEncoder.encode(redirectUri, "utf-8"));
    if (scope != null)
        result.append("&scope=").append(URLEncoder.encode(scope, "utf-8"));
    if (state != null)
        result.append("&state=").append(URLEncoder.encode(state, "utf-8"));
    return result.toString();
}

From source file:com.ihelpoo.app.common.QQWeiboHelper.java

/**
* ?/*from  w ww .j a v a  2s. c o  m*/
* @param activity
* @param title
* @param url
*/
public static void shareToQQ(Activity activity, String title, String url) {
    String URL = Share_URL;
    try {
        URL += "&title=" + URLEncoder.encode(title, HTTP.UTF_8) + "&url=" + URLEncoder.encode(url, HTTP.UTF_8)
                + "&appkey=" + Share_AppKey + "&source=" + Share_Source + "&site=" + Share_Site;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Uri uri = Uri.parse(URL);
    activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}

From source file:Main.java

public static String getUrlEncode(String str, String codeType) throws UnsupportedEncodingException {
    if (str == null || "".equals(str))
        return null;

    String resultString = null;//from   w  ww  .ja  va2s.  c  o m
    if (codeType == null || "".equals(codeType))
        resultString = URLEncoder.encode(str, "UTF-8");
    else
        resultString = URLEncoder.encode(str, codeType);

    return resultString.toLowerCase();
}

From source file:com.noelportugal.amazonecho.WitAi.java

public String getJson(String text) {
    String output = "";
    try {/*from   w ww. j a v  a 2  s  .c o m*/

        HttpGet httpGet = new HttpGet(
                "https://api.wit.ai/message?v=20141226&q=" + URLEncoder.encode(text, "UTF-8"));
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
        HttpResponse httpResponse = httpclient.execute(httpGet);
        StatusLine responseStatus = httpResponse.getStatusLine();
        int statusCode = responseStatus.getStatusCode();
        if (statusCode == 200) {
            httpResponse.getEntity();
            output = new BasicResponseHandler().handleResponse(httpResponse);
        }
    } catch (Exception e) {
        System.err.println("httpGet Error: " + e.getMessage());
    }

    return output;
}

From source file:com.microsoft.office365.connectmicrosoftgraph.ConnectUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(Constants.MICROSOFT_GRAPH_API_ENDPOINT_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*from  w  ww.j av a 2 s  . c  o m*/

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();
}

From source file:org.ambraproject.wombat.service.remote.ApiAddress.java

private static String encodePath(String path) {
    try {//from  w  ww .  j a  v  a  2s  .c om
        return URLEncoder.encode(path, Charsets.UTF_8.toString());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.nominanuda.web.http.FormEncodingUtf8Test.java

@Test
public void test() throws IOException {
    String ori = " ";
    assertEquals(ori, g(URLEncoder.encode(ori, "UTF-8"), CT_WWW_FORM_URLENCODED_CS_UTF8));
    assertEquals(ori, g(URLEncoder.encode(ori, "ISO-8859-1"), CT_WWW_FORM_URLENCODED + ";charset=ISO-8859-1"));
    assertEquals(ori, g(URLEncoder.encode(ori, "UTF-8"), CT_WWW_FORM_URLENCODED));
    assertEquals(ori, g1(ori.getBytes(CS_UTF_8), CT_WWW_FORM_URLENCODED_CS_UTF8));
    assertEquals(ori, g1(ori.getBytes("ISO-8859-1"), CT_WWW_FORM_URLENCODED + ";charset=ISO-8859-1"));
}

From source file:api.APICall.java

public String loginBucket(String targetURL, String username, String password) {
    String api = "login";
    targetURL = targetURL + api;/*from   w  w w.  j  a  v a 2s  .co m*/
    String urlParameters;
    try {

        urlParameters = "user-name=" + URLEncoder.encode(username, enc) + "&password="
                + URLEncoder.encode(password, enc);

        String response = executePost(targetURL, urlParameters);
        return response;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;

}

From source file:com.apabi.qrcode.utils.EncodeUtils.java

/**
 * URL ?./*from w w w .  j a va 2 s  .  c  o  m*/
 */
public static String urlEncode(final String input, final String encoding) {
    try {
        return URLEncoder.encode(input, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unsupported Encoding Exception", e);
    }
}