/** * 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()); }
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); } }
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()); }
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(); }
@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"); }
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(); }
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; }
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(); }
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(); }
/** * 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; }
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(); }
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(); }
/** * 开始解析发送参数 */ 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); } }
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(); }
/** * 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()); }
/** * 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; }
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(); }
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); } }
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(); }
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(); }
/** * 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; }
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; }
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; }
/** * 显示标签 * * @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 ""; }
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(); }
/** * 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; }
/** * 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; } }
private static String encode(String value) { try { return URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding"); } }
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(); }
public static String urlEncodeUTF8(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException(e); } }
/** * 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; }
/** * 拼接字符串 * * @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); }
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())); }
/** * 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); } }
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); } }
@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); } }
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(); }
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; } }
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"); }
public String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception { String url = "https://translate.googleapis.com/translate_a/single?"+ "client=gtx&"+ "sl=" + langFrom + "&tl=" + langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8"); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0"); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String result = parseResult(response.toString()); if(result.equals("")){ return word; } else { return result;} }