Java Code Examples for java.net.URLEncoder

The following are top voted examples for showing how to use java.net.URLEncoder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: JavaHTTP   File: HttpRequester.java   View source code 6 votes vote down vote up
/**
 * Sets the URL to request.
 * @param url    The URL without query
 * @param params A map that contains URL query parameters into key and value. The key and value
 *               will be percent encoded as UTF-8.
 * @throws UnsupportedEncodingException Occurs when UTF-8 is not available.
 * @since v1.1.0
 */
@NotNull
public HttpRequester setUrl(@NotNull String url, @NotNull Map<String, String> params)
		throws UnsupportedEncodingException
{
	StringBuilder queryString = new StringBuilder();

	// Convert the params map into a query string.
	for (Map.Entry<String, String> entry : params.entrySet())
	{
		if (queryString.length() != 0)
			queryString.append('&');

		String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
		String encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8");

		queryString.append(encodedKey);
		queryString.append('=');
		queryString.append(encodedValue);
	}

	return setUrl(url + '?' + queryString.toString());
}
 
Example 2
Project: SearchRestaurant   File: MainActivity.java   View source code 6 votes vote down vote up
private void searchKeywordNextPage(String keyword) {
    try {
        String unitStr = URLEncoder.encode(keyword, "utf8");  //字體要utf8編碼
        StringBuilder sb = new StringBuilder(ConfigUtil.GOOGLE_SEARCH_API);
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&radius=" + radius);
        sb.append("&language =" + language);
        sb.append("&types=" + keyword);
        sb.append("&sensor=true");
        sb.append("&key=" + ConfigUtil.API_KEY_GOOGLE_MAP);  //server key
        sb.append("&pagetoken=" + page_token);
        MainActivity.PlacesTask placesTask = new MainActivity.PlacesTask(MainActivity.this);
        Log.v(TAG, sb.toString());
        placesTask.execute(sb.toString());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.i(ConfigUtil.TAG, "Exception:" + e);
    }
}
 
Example 3
Project: Weather-Android   File: GenericRequestTask.java   View source code 6 votes vote down vote up
private URL provideURL(String[] coords) throws UnsupportedEncodingException, MalformedURLException {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    String apiKey = sp.getString("apiKey", activity.getResources().getString(R.string.apiKey));

    StringBuilder urlBuilder = new StringBuilder("http://api.openweathermap.org/data/2.5/");
    urlBuilder.append(getAPIName()).append("?");
    if (coords.length == 2) {
        urlBuilder.append("lat=").append(coords[0]).append("&lon=").append(coords[1]);
    } else {
        final String city = sp.getString("city", Constants.DEFAULT_CITY);
        urlBuilder.append("q=").append(URLEncoder.encode(city, "UTF-8"));
    }
    urlBuilder.append("&lang=").append(getLanguage());
    urlBuilder.append("&mode=json");
    urlBuilder.append("&appid=").append(apiKey);

    return new URL(urlBuilder.toString());
}
 
Example 4
Project: ConcealSharedPreference-Android   File: ConverterListUtils.java   View source code 6 votes vote down vote up
static String convertMapToString(Map<String,String> maps){
    StringBuilder stringBuilder = new StringBuilder();

    for (String key : maps.keySet()) {
        if (stringBuilder.length() > 0) {
            stringBuilder.append("&");
        }
        String value = maps.get(key);
        try {
            stringBuilder.append((key != null ? URLEncoder.encode(key, "UTF-8") : ""));
            stringBuilder.append("=");
            stringBuilder.append(value != null ? URLEncoder.encode(value, "UTF-8") : "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("This method requires UTF-8 encoding support", e);
        }
    }

    return stringBuilder.toString();
}
 
Example 5
Project: shuzheng   File: SSOController.java   View source code 6 votes vote down vote up
@ApiOperation(value = "认证中心首页")
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(HttpServletRequest request) throws Exception {
    String appid = request.getParameter("appid");
    String backurl = request.getParameter("backurl");
    if (StringUtils.isBlank(appid)) {
        throw new RuntimeException("无效访问!");
    }
    // 判断请求认证系统是否注册
    UpmsSystemExample upmsSystemExample = new UpmsSystemExample();
    upmsSystemExample.createCriteria()
            .andNameEqualTo(appid);
    int count = upmsSystemService.countByExample(upmsSystemExample);
    if (0 == count) {
        throw new RuntimeException(String.format("未注册的系统:%s", appid));
    }
    return "redirect:/sso/login?backurl=" + URLEncoder.encode(backurl, "utf-8");
}
 
Example 6
Project: browser   File: HttpPostTaskInner.java   View source code 6 votes vote down vote up
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        if(pair!=null&&pair.getName()!=null&&pair.getValue()!=null){
         result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
         result.append("=");
         result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
        
    }

    return result.toString();
}
 
Example 7
Project: dswork   File: WebFilter.java   View source code 6 votes vote down vote up
public static String getLoginURL(String url)
{
	String _url = loginURL;
	try
	{
		if(url == null || url.length() == 0)
		{
			if(systemURL.length() > 0)
			{
				_url = loginURL + "?service=" + URLEncoder.encode(systemURL, "UTF-8");
			}
		}
		else
		{
			_url = loginURL + "?service=" + URLEncoder.encode(url, "UTF-8");
		}
	}
	catch(Exception e)
	{
		_url = loginURL;
	}
	return _url;
}
 
Example 8
Project: bubichain-sdk-java   File: PostParameter.java   View source code 6 votes vote down vote up
public static String encodeParameters(PostParameter[] httpParams) {
    if (null == httpParams) {
        return "";
    }
    StringBuffer buf = new StringBuffer();
    for (int j = 0; j < httpParams.length; j++) {
        if (httpParams[j].isFile()) {
            throw new IllegalArgumentException("parameter [" + httpParams[j].name + "]should be text");
        }
        if (j != 0) {
            buf.append("&");
        }
        try {
            buf.append(URLEncoder.encode(httpParams[j].name, "UTF-8"))
                    .append("=").append(URLEncoder.encode(httpParams[j].value, "UTF-8"));
        } catch (java.io.UnsupportedEncodingException neverHappen) {
        }
    }
    return buf.toString();

}
 
Example 9
Project: NeterraProxy   File: Utils.java   View source code 6 votes vote down vote up
static String generatePlaylist(String contentJson, JsonObject channelsJson, String host, int port) {
    JsonArray neterraContentArray = new JsonParser().parse(contentJson).getAsJsonObject()
            .get("tv_choice_result").getAsJsonArray();

    StringBuilder m3u8 = new StringBuilder("#EXTM3U\n");
    for (int i = 0; i < neterraContentArray.size(); i++) {
        JsonObject channel = neterraContentArray.get(i).getAsJsonArray().get(0).getAsJsonObject();
        String chanId = channel.get("issues_id").getAsString();
        String chanName = channel.get("issues_name").getAsString();
        String tvgId = "";
        String tvgName = "";
        String group = "";
        String logo = "";

        JsonObject definedChannel  = channelsJson.getAsJsonObject(chanId);
        if (definedChannel != null) {
            chanName = definedChannel.get("name").getAsString();
            tvgId = definedChannel.get("tvg-id").getAsString();
            tvgName = definedChannel.get("tvg-name").getAsString();
            group = definedChannel.get("group").getAsString();
            logo = definedChannel.get("logo").getAsString();
        }
        String encodedChanName = null;
        try {
            encodedChanName = URLEncoder.encode(chanName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        m3u8.append(String.format("#EXTINF:-1 tvg-id=\"%s\" tvg-name=\"%s\" tvg-logo=\"%s\" " +
                        "group-title=\"%s\",%s\nhttp://%s:%s/playlist.m3u8?ch=%s&name=%s\n",
                tvgId, tvgName, logo, group, chanName, host, port, chanId, encodedChanName));
    }

    return m3u8.toString();
}
 
Example 10
Project: joai-project   File: HarvestReportAction.java   View source code 6 votes vote down vote up
private final String getParamsString(Hashtable excludeParams, HttpServletRequest request) {
	if (request == null)
		return null;

	Enumeration params = request.getParameterNames();
	String param;
	String vals[];
	StringBuffer addParams = new StringBuffer();
	try {
		while (params.hasMoreElements()) {
			param = (String) params.nextElement();
			if (!excludeParams.containsKey(param)) {
				vals = request.getParameterValues(param);
				for (int i = 0; i < vals.length; i++) {
					addParams.append("&" + param + "=" + URLEncoder.encode(vals[i], "utf-8"));
				}
			}
		}
	} catch (Exception e) {
		addParams.toString();
	}
	return addParams.toString();
}
 
Example 11
Project: RoughWorld   File: WebSecurity.java   View source code 6 votes vote down vote up
/**
 * URL-encodes everything between "/"-characters.
 * Encodes spaces as '%20' instead of '+'.
 */
public static String encodeUri( String uri )
{
	String newUri = "";
	StringTokenizer st = new StringTokenizer( uri, "/ ", true );
	while ( st.hasMoreTokens())
	{
		String tok = st.nextToken();
		if ( tok.equals( "/" ))
			newUri += "/";
		else if ( tok.equals( " " ))
			newUri += "%20";
		else
		{
			newUri += URLEncoder.encode( tok );
			// For Java 1.4 you'll want to use this instead:
			// try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( UnsupportedEncodingException uee )
		}
	}
	return newUri;
}
 
Example 12
Project: pay   File: WebUtils.java   View source code 6 votes vote down vote up
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
    if (params == null || params.isEmpty()) {
        return null;
    }

    StringBuilder query = new StringBuilder();
    Set<Entry<String, String>> entries = params.entrySet();
    boolean hasParam = false;

    for (Entry<String, String> entry : entries) {
        String name = entry.getKey();
        String value = entry.getValue();
        // 忽略参数名或参数值为空的参数
        if (StringUtils.areNotEmpty(name, value)) {
            if (hasParam) {
                query.append("&");
            } else {
                hasParam = true;
            }

            query.append(name).append("=").append(URLEncoder.encode(value, charset));
        }
    }

    return query.toString();
}
 
Example 13
Project: provadevida   File: EnviarFotoActivity.java   View source code 6 votes vote down vote up
public String getPostDataString(JSONObject params) throws Exception {

            StringBuilder result = new StringBuilder();
            boolean first = true;

            Iterator<String> itr = params.keys();

            while(itr.hasNext()){

                String key= itr.next();
                Object value = params.get(key);

                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(key, "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(value.toString(), "UTF-8"));

            }
            return result.toString();
        }
 
Example 14
Project: JBase   File: BaseInterceptor.java   View source code 6 votes vote down vote up
/**
 * 开始解析发送参数
 */
private void sendLogRequest(Request request) throws IOException {
    if (request != null) {
        String body = "";
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            //编码设为UTF-8
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = request.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
            body = buffer.readString(charset);
            //如果你出现中文参数乱码情况,请进行URL解码处理!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            body = URLEncoder.encode(body, "UTF-8");
        }
        LogUtils.i("发送----" + "method:" + request.method() + "  url:" + request.url() + "  body:" + body);
    }
}
 
Example 15
Project: jarling   File: HttpParameter.java   View source code 6 votes vote down vote up
public static String encodeParameters(HttpParameter[] httpParameters){
    if (null == httpParameters) { return ""; }

    StringBuilder paramBuff = new StringBuilder();

    for (int i = 0; i < httpParameters.length; i++){
        try {
            paramBuff.append(URLEncoder.encode(httpParameters[i].getName(), "UTF-8"))
                    .append("=")
                    .append(URLEncoder.encode(httpParameters[i].getValue(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (i != httpParameters.length - 1){
            paramBuff.append("&");
        }
    }
    return paramBuff.toString();
}
 
Example 16
Project: lams   File: InstallTask.java   View source code 6 votes vote down vote up
/**
 * Execute the requested operation.
 *
 * @exception BuildException if an error occurs
 */
public void execute() throws BuildException {

    super.execute();
    if (path == null) {
        throw new BuildException
            ("Must specify 'path' attribute");
    }
    if ((config == null) && (war == null)) {
        throw new BuildException
            ("Must specify at least one of 'config' and 'war'");
    }
    StringBuffer sb = new StringBuffer("/install?path=");
    sb.append(URLEncoder.encode(this.path));
    if (config != null) {
        sb.append("&config=");
        sb.append(URLEncoder.encode(config));
    }
    if (war != null) {
        sb.append("&war=");
        sb.append(URLEncoder.encode(war));
    }
    execute(sb.toString());

}
 
Example 17
Project: Java-APIs   File: SESClient.java   View source code 6 votes vote down vote up
/**
 * Sends request which increases popularity counter for term
 * @param id ID of term to update
 * @throws SESException SES exception
 */
public void increasePopularity(String id) throws SESException {
	logger.info("increasePopularity - id: '" + id + "'");

	URL url = null;

	try {
		StringBuffer query = new StringBuffer();
		query.append("?TBDB=" + URLEncoder.encode(getOntology(), "UTF8"));
		query.append("&template=" + URLEncoder.encode(getTemplate(), "UTF8"));
		query.append("&service=increase_popularity");
		query.append("&id=" + URLEncoder.encode(id, "UTF8"));
		query.append(getLanguageChoice());

		url = getURLImpl(query.toString());
		if (logger.isDebugEnabled()) logger.debug("URL: " + url.toExternalForm());
	} catch (UnsupportedEncodingException e) {
		throw new SESException("UnsupportedEncodingException: " + e.getMessage());
	}

	getSemaphore(url);
	return;
}
 
Example 18
Project: CustomAndroidOneSheeld   File: FoursquareUtils.java   View source code 6 votes vote down vote up
public static String encodeUrl(Bundle parameters) {
    if (parameters == null) {
        return "";
    }

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : parameters.keySet()) {
        if (first)
            first = false;
        else
            sb.append("&v=20140201" + "&");
        try {
            sb.append(URLEncoder.encode(key, "UTF-8") + "="
                    + URLEncoder.encode(parameters.getString(key), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            Log.e("TAG", "FoursquareUti::encodeUrl::UnsupportedEncodingException", e);
        }
    }
    return sb.toString();
}
 
Example 19
Project: Thrush   File: HttpRequest.java   View source code 6 votes vote down vote up
private static String getQueueCountParam(Ticket ticket, TrainQuery query) {
    String token = Optional.ofNullable(ResultManager.get("repeatSubmitToken")).map(thrushResult -> (String)thrushResult.getValue()).orElse(StringUtils.EMPTY);
    String purposeCodes = Optional.ofNullable(ResultManager.get("purposeCodes")).map(thrushResult -> (String)thrushResult.getValue()).orElse(StringUtils.EMPTY);

    StringBuilder builder = new StringBuilder();
    try {
        builder.append("train_date=").append(formatDate(query)).append("&train_no=").append(ticket.getTrainLongNo()).append("&stationTrainCode=")
                .append(ticket.getTrainNo()).append("&seatType=").append(SeatConfig.getSeatType(query.getSeat())).append("&fromStationTelecode=").append(ticket.getFromStationTelecode())
                .append("&toStationTelecode=").append(ticket.getToStationTelecode()).append("&leftTicket=").append(URLEncoder.encode(ticket.getLeftTicket(), "UTF-8")).append("&purpose_codes=").append(purposeCodes)
                .append("&train_location=").append(ticket.getTrainLocation()).append("&_json_att=&REPEAT_SUBMIT_TOKEN=").append(token);

        return builder.toString();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

}
 
Example 20
Project: UnversityFinance   File: HttpConnectUtils.java   View source code 6 votes vote down vote up
public static String getURLWithParams(String address, HashMap<String,String> params) throws UnsupportedEncodingException {
    //设置编码
    final String encode = "UTF-8";
    StringBuilder url = new StringBuilder(address);
    url.append("?");
    //将map中的key,value构造进入URL中
    int index = 1;
    for(Map.Entry<String, String> entry : params.entrySet()) {
        if (index > 1) {
            url.append("&");
        }
        url.append(entry.getKey()).append("=");
        url.append(URLEncoder.encode(entry.getValue(), encode));
        index++;
    }

    return url.toString();
}
 
Example 21
Project: Server-Quickstart-Vert.x   File: NetworkingHelper.java   View source code 6 votes vote down vote up
static byte[] createParamBytes(Map<String, Object> params) {
	// Body data to byte[]
	
	StringBuilder requestData = new StringBuilder();
	
	for(String key : params.keySet()) {
		String value = String.valueOf(params.get(key));
		try {
			requestData.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	String requestAddressStr = requestData.toString();
	requestAddressStr = requestAddressStr.substring(0, requestAddressStr.length() - 1);
	return requestAddressStr.getBytes();
}
 
Example 22
Project: fort_j   File: Strings.java   View source code 6 votes vote down vote up
/**
 * Synonym for <tt>URLEncoder.encode(String, "UTF-8")</tt>.
 *
 * <P>Used to ensure that HTTP query strings are in proper form, by escaping
 * special characters such as spaces.
 *
 * <P>It is important to note that if a query string appears in an <tt>HREF</tt>
 * attribute, then there are two issues - ensuring the query string is valid HTTP
 * (it is URL-encoded), and ensuring it is valid HTML (ensuring the
 * ampersand is escaped).
 */
@ApiMethod
@Comment(value = "Does URLEncoder.encode() but throws a RuntimeException instead of an UnsupportedEncodingException")
public static String forURL(String aURLFragment)
{
   String result = null;
   try
   {
      result = URLEncoder.encode(aURLFragment, "UTF-8");
   }
   catch (UnsupportedEncodingException ex)
   {
      throw new RuntimeException("UTF-8 not supported", ex);
   }
   return result;
}
 
Example 23
Project: pgcodekeeper   File: EventRegister.java   View source code 6 votes vote down vote up
private File getStorageFile(UsageEventProperties properties) {
    File directory = getStorageDirectory();
    if (directory != null) {
        String name = properties.type.getActionName() + "-" + properties.countEventLabel;
        try {
            name = URLEncoder.encode(name, "UTF-8");
            if (name.length() > 40) {
                name = (UUID.nameUUIDFromBytes(name.getBytes())).toString();
            }
            return new File(directory, name);
        } catch (UnsupportedEncodingException e) {
            Log.log(Log.LOG_ERROR, e.getMessage());
        }
    }
    return null;
}
 
Example 24
Project: java-magento-client   File: MagentoHttpComponent.java   View source code 5 votes vote down vote up
public String escape(String text) {
   String result = text;
   try{
      result = URLEncoder.encode(text, "UTF-8");
   }
   catch (UnsupportedEncodingException e) {
      logger.error("Failed to escape " + text, e);
   }
   return result;
}
 
Example 25
Project: My-Blog   File: Commons.java   View source code 5 votes vote down vote up
/**
 * 显示标签
 *
 * @param tags
 * @return
 */
public static String show_tags(String tags) throws UnsupportedEncodingException {
    if (StringUtils.isNotBlank(tags)) {
        String[] arr = tags.split(",");
        StringBuffer sbuf = new StringBuffer();
        for (String c : arr) {
            sbuf.append("<a href=\"/tag/" + URLEncoder.encode(c, "UTF-8") + "\">" + c + "</a>");
        }
        return sbuf.toString();
    }
    return "";
}
 
Example 26
Project: GoGo   File: QueryController.java   View source code 5 votes vote down vote up
private String sendGet( String message) throws Exception {
    String api_ai_token = "bearer a7d81f6de8154d748b48d9ae6913a517";
    String url = "https://api.api.ai/v1/query?query="+ URLEncoder.encode(message,"UTF-8") +"&lang=en&sessionId=1732812321";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("Authorization", api_ai_token);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

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

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

    //print result
    System.out.println(response.toString());
    return response.toString();
}
 
Example 27
Project: pScrobbler   File: StringUtilities.java   View source code 5 votes vote down vote up
/**
 * URL Encodes the given String <code>s</code> using the UTF-8 character encoding.
 *
 * @param s a String
 * @return url encoded string
 */
public static String encode(String s) {
	if(s == null)
		return null;
	try {
		return URLEncoder.encode(s, "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// utf-8 always available
	}
	return null;
}
 
Example 28
Project: lams   File: HTTPTransportUtils.java   View source code 5 votes vote down vote up
/**
 * URL Encode the given string.
 * 
 * @param value the string to encode
 * @return the encoded string
 */
public static String urlEncode(String value) {
    try {
        return URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // UTF-8 encoding is required to be supported by all JVMs
        return null;
    }
}
 
Example 29
Project: vertx-kubernetes-workshop   File: PortfolioServiceImpl.java   View source code 5 votes vote down vote up
private static String encode(String value) {
    try {
        return URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Unsupported encoding");
    }
}
 
Example 30
Project: amigo-chatbot   File: HttpClient.java   View source code 5 votes vote down vote up
public static String getIntentFromWitAI(String message) throws UnirestException, UnsupportedEncodingException {
    String url = "https://api.wit.ai/message?v=20160526&q=" + URLEncoder.encode(message, "UTF-8");
    HttpResponse<String> response = Unirest.get(url)
            .header("authorization", "Bearer " + System.getenv("WIT_AI_SERVER_ACCESS_TOKEN"))
            .header("cache-control", "no-cache")
            .asString();
    return response.getBody();
}
 
Example 31
Project: http-facade   File: Util.java   View source code 5 votes vote down vote up
public static String urlEncodeUTF8(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedOperationException(e);
    }
}
 
Example 32
Project: lams   File: LamsSecurityUtil.java   View source code 5 votes vote down vote up
/**
    * Takes care about blank values. Besides, escapes CSV sensitive symbols (commas, quotes, etc) and then encodes it to be sent as a URL parameter.
    * 
    * @param value
    * @param CSV
    * @return
    * @throws UnsupportedEncodingException
    */
   private static String escapeValue(String value) throws UnsupportedEncodingException {
final String DUMMY_VALUE = "-";

String notBlankValue = StringUtils.isBlank(value) ? DUMMY_VALUE : value;
String escapedCsv = StringEscapeUtils.escapeCsv(notBlankValue);
String encodedValue = URLEncoder.encode(escapedCsv, "utf8");

return encodedValue;
   }
 
Example 33
Project: pay4j   File: StringUtil.java   View source code 5 votes vote down vote up
/**
 * 拼接字符串
 *
 * @param map     对象
 * @param charset 字符集
 * @param encode  是否编码
 * @param withQuota 是否加引号
 * @return str
 */
public static String toJoinForSign(Map<String, String> map, Charset charset, boolean encode, boolean withQuota) {
    map.remove("sign");
    map.remove("sign_type");
    map = new TreeMap<String, String>(map);
    StringBuilder sb = new StringBuilder();
    Set<Map.Entry<String, String>> set = map.entrySet();
    try {

        for (Map.Entry<String, String> entry : set) {
            if (Strings.isNullOrEmpty(entry.getValue())) {
                continue;
            }
            String value = entry.getValue();
            if (withQuota) {
                value = new StringBuilder("\"").append(value).append("\"").toString();
            }
            sb.append(entry.getKey()).append("=");
            if (encode) {
                sb.append(URLEncoder.encode(value, charset.name()));
            } else {
                sb.append(value);
            }
            sb.append("&");
        }
    } catch (UnsupportedEncodingException e) {

    }
    return sb.substring(0, sb.length() - 1);
}
 
Example 34
Project: GitHub   File: DeviceInfoTests.java   View source code 5 votes vote down vote up
public void testGetMetrics() throws UnsupportedEncodingException, JSONException {
    final JSONObject json = new JSONObject();
    json.put("_device", DeviceInfo.getDevice());
    json.put("_os", DeviceInfo.getOS());
    json.put("_os_version", DeviceInfo.getOSVersion());
    if (!"".equals(DeviceInfo.getCarrier(getContext()))) { // ensure tests pass on non-cellular devices
        json.put("_carrier", DeviceInfo.getCarrier(getContext()));
    }
    json.put("_resolution", DeviceInfo.getResolution(getContext()));
    json.put("_density", DeviceInfo.getDensity(getContext()));
    json.put("_locale", DeviceInfo.getLocale());
    json.put("_app_version", DeviceInfo.getAppVersion(getContext()));
    final String expected = URLEncoder.encode(json.toString(), "UTF-8");
    assertNotNull(expected);
    assertEquals(expected, DeviceInfo.getMetrics(getContext()));
}
 
Example 35
Project: GitHub   File: Request.java   View source code 5 votes vote down vote up
/**
 * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
 */
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
    StringBuilder encodedParams = new StringBuilder();
    try {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
            encodedParams.append('=');
            encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
            encodedParams.append('&');
        }
        return encodedParams.toString().getBytes(paramsEncoding);
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
    }
}
 
Example 36
Project: hadoop-oss   File: KMSClientProvider.java   View source code 5 votes vote down vote up
private URL createURL(String collection, String resource, String subResource,
    Map<String, ?> parameters) throws IOException {
  try {
    StringBuilder sb = new StringBuilder();
    sb.append(kmsUrl);
    if (collection != null) {
      sb.append(collection);
      if (resource != null) {
        sb.append("/").append(URLEncoder.encode(resource, UTF8));
        if (subResource != null) {
          sb.append("/").append(subResource);
        }
      }
    }
    URIBuilder uriBuilder = new URIBuilder(sb.toString());
    if (parameters != null) {
      for (Map.Entry<String, ?> param : parameters.entrySet()) {
        Object value = param.getValue();
        if (value instanceof String) {
          uriBuilder.addParameter(param.getKey(), (String) value);
        } else {
          for (String s : (String[]) value) {
            uriBuilder.addParameter(param.getKey(), s);
          }
        }
      }
    }
    return uriBuilder.build().toURL();
  } catch (URISyntaxException ex) {
    throw new IOException(ex);
  }
}
 
Example 37
Project: MCBot   File: CommandLMGTFY.java   View source code 5 votes vote down vote up
@Override
public void process(CommandContext ctx) throws CommandException {
    if (ctx.getArgs().size() < 1) {
        throw new CommandException("Not enough arguments.");
    }
    int iie = ctx.getFlags().containsKey(FLAG_IE) ? 1 : 0;
    StringBuilder url = new StringBuilder("<http://lmgtfy.com/?iie=").append(iie).append("&q=");
    String arg = ctx.getArg(ARG_QUERY);
    try {
        ctx.reply(url.append(URLEncoder.encode(ctx.sanitize(arg), Charsets.UTF_8.name())).append(">").toString());
    } catch (UnsupportedEncodingException e) {
        throw new CommandException(e);
    }
}
 
Example 38
Project: MPay   File: MAliPayInfoUtil.java   View source code 5 votes vote down vote up
private static String signPayInfo(String orderInfo, String rsaKey) {
    String sign = SignUtils.sign(orderInfo, rsaKey);
    try {
        rsaKey = URLEncoder.encode(sign, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return orderInfo + "&sign=\"" + rsaKey + "\"&" + getSignType();
}
 
Example 39
Project: hashsdn-controller   File: LocalSnapshotStore.java   View source code 5 votes vote down vote up
private static String encode(final String str) {
    try {
        return URLEncoder.encode(str, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        // Shouldn't happen
        LOG.warn("Error encoding {}", str, e);
        return str;
    }
}
 
Example 40
Project: cas4.0.x-server-wechat   File: LoginAsCredentialsRequestorCompatibilityTests.java   View source code 5 votes vote down vote up
public void testBlankGateway() throws UnsupportedEncodingException {
    final String SERVICE = URLEncoder.encode("http://www.cnn.com", "UTF-8");
    final String URL = "/login?service=" + SERVICE + "&gateway=";

    beginAt(URL);

    // test that we're now at cnn.com rather than at the login form.
    assertTextPresent("cnn.com");
    assertFormElementNotPresent("lt");
}