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:ca.uhn.fhir.rest.client.BaseHttpClientInvocation.java

protected static void appendExtraParamsWithQuestionMark(Map<String, List<String>> theExtraParams,
        StringBuilder theUrlBuilder, boolean theWithQuestionMark) {
    if (theExtraParams == null) {
        return;/*  w ww  .j a va 2 s  .co  m*/
    }
    boolean first = theWithQuestionMark;

    if (theExtraParams != null && theExtraParams.isEmpty() == false) {
        for (Entry<String, List<String>> next : theExtraParams.entrySet()) {
            for (String nextValue : next.getValue()) {
                if (first) {
                    theUrlBuilder.append('?');
                    first = false;
                } else {
                    theUrlBuilder.append('&');
                }
                try {
                    theUrlBuilder.append(URLEncoder.encode(next.getKey(), "UTF-8"));
                    theUrlBuilder.append('=');
                    theUrlBuilder.append(URLEncoder.encode(nextValue, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new Error("UTF-8 not supported - This should not happen");
                }
            }
        }
    }
}

From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java

@Override
protected Void doInBackground(Void... voids) {
    try {/*ww  w . j  a v a2 s .co  m*/

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"),
                ContentType.create("Multipart/related", "UTF-8"));
        builder.addPart("image", new FileBody(new File(path)));

        InputStream inputStream = null;
        HttpClient httpClient = AndroidHttpClient.newInstance("Android");

        String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, "");
        String encodeCarNo = "";

        if (false == carNo.equals("")) {
            encodeCarNo = URLEncoder.encode(carNo, "UTF-8");
        }
        HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo);
        httpPost.setEntity(builder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:jp.mixi.android.sdk.util.UrlUtils.java

/**
 * Bundle???//w  w w.  j a  v a  2 s  .  c o m
 * 
 * @param params ?Bundle
 * @return ???String
 */
public static String encodeUrlForBundle(Bundle params) {
    if (params == null) {
        return "";
    }

    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for (String key : params.keySet()) {
        if (first) {
            first = false;
        } else {
            builder.append(PARAM_SEPARATOR);
        }
        try {
            builder.append(URLEncoder.encode(key, HTTP.UTF_8) + EQUAL
                    + URLEncoder.encode(params.getString(key), HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }
    }
    return builder.toString();
}

From source file:DBpediaSpotlightClient.java

@Override
public List<DBpediaResource> extract(Text text) throws AnnotationException {

    LOG.info("Querying API.");
    String spotlightResponse;//from  w ww . jav  a  2 s. c om
    try {
        GetMethod getMethod = new GetMethod(API_URL + "rest/annotate/?" + "confidence=" + CONFIDENCE
                + "&support=" + SUPPORT + "&text=" + URLEncoder.encode(text.text(), "utf-8"));
        getMethod.addRequestHeader(new Header("Accept", "application/json"));

        spotlightResponse = request(getMethod);
    } catch (UnsupportedEncodingException e) {
        throw new AnnotationException("Could not encode text.", e);
    }

    assert spotlightResponse != null;

    JSONObject resultJSON = null;
    JSONArray entities = null;

    try {
        resultJSON = new JSONObject(spotlightResponse);
        entities = resultJSON.getJSONArray("Resources");
    } catch (JSONException e) {
        throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
    }

    LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
    for (int i = 0; i < entities.length(); i++) {
        try {
            JSONObject entity = entities.getJSONObject(i);
            resources.add(new DBpediaResource(entity.getString("@URI"),
                    Integer.parseInt(entity.getString("@support"))));

        } catch (JSONException e) {
            LOG.error("JSON exception " + e);
        }

    }

    return resources;
}

From source file:com.pfw.popsicle.common.Encodes.java

/**
 * URL ?, EncodeUTF-8. //  w  w w .ja  v a  2  s .co  m
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
    }
    return part;
}

From source file:Main.java

public static String urlencode(Map<String, ?> data) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, ?> i : data.entrySet()) {
        try {//from w w  w.j  a  v  a2 s.com
            sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

From source file:com.intuit.tank.http.keyvalue.KeyValueRequest.java

@SuppressWarnings("rawtypes")
public String getBody() {
    Set set = this.postData.entrySet();
    Iterator iter = set.iterator();
    String body = "";

    while (iter.hasNext()) {
        try {/*w  w  w .  jav a2 s .co m*/
            Map.Entry mapEntry = (Map.Entry) iter.next();
            String key = mapEntry.getKey() != null ? URLEncoder.encode((String) mapEntry.getKey(), "UTF-8")
                    : "";
            String value = mapEntry.getValue() != null
                    ? URLEncoder.encode((String) mapEntry.getValue(), "UTF-8")
                    : "";

            if (StringUtils.isEmpty(body)) {
                body = key + "=" + value;
            } else {
                body = body + "&" + key + "=" + value;
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    return body;
}

From source file:com.lyh.licenseworkflow.web.filter.LoginFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    StringBuffer buffer = httpRequest.getRequestURL();// url
    String queryString = httpRequest.getQueryString();// ?
    HttpSession session = httpRequest.getSession();
    //?// ww w .  j  a v a 2s  . c  o  m
    String wonderUrl = URLEncoder.encode(httpRequest.getRequestURI() + "?" + httpRequest.getQueryString(),
            "UTF-8");
    String fullUrl = buffer.toString();// url???web??
    boolean checkPermission = true;// ?????CSSJSJVM???
    for (String ingoreUrl : ingoreUrls) {
        if (fullUrl.indexOf(ingoreUrl) != -1) {// URL???????
            checkPermission = false;
            break;
        }
    }
    if (!checkPermission) {// ???
        filterChain.doFilter(httpRequest, httpResponse);
    } else {// ?????
        User loginUser = (User) httpRequest.getSession().getAttribute(LicenseWorkFlowConstants.SESSION_USER);
        if (loginUser == null) {
            //??
            //session
            //                httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.action?wonderUrl=" + wonderUrl);
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.action");
            return;
        } else {
            filterChain.doFilter(httpRequest, httpResponse);
        }
    }
}

From source file:org.shredzone.cilla.plugin.social.TwitterSocialHandler.java

/**
 * twitter//w  ww .  j av a 2  s . com
 */
@SocialBookmark(icon = "twitter.png")
@Priority(10)
public String twitterSocialBookmark(@PageLink(shortened = true) String pageLink, @PageTitle String pageTitle) {
    String tweet = pageLink + " - " + pageTitle;

    if (tweet.length() > MAX_TWEET_LENGTH) {
        tweet = tweet.substring(0, MAX_TWEET_LENGTH);
    }

    try {
        return "http://twitter.com/home?status=" + URLEncoder.encode(tweet, "utf-8");
    } catch (UnsupportedEncodingException ex) {
        throw new InternalError("no utf-8");
    }
}