java.net.URLEncoder Java Examples
The following examples show how to use
java.net.URLEncoder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CookieUtils.java From mogu_blog_v2 with Apache License 2.0 | 6 votes |
/** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) { cookie.setMaxAge(cookieMaxage); } if (null != request) {// 设置域名的cookie String domainName = getDomainName(request); System.out.println(domainName); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } }
Example #2
Source File: SolutionResourceIntTest.java From cubeai with Apache License 2.0 | 6 votes |
public void getMatchingModels()throws Exception{ String portType = "output"; // String protobufJsonString = "[{\"role\":\"repeated\",\"tag\":\"1\",\"type\":\"string\"},{\"role\":\"repeated\",\"tag\":\"2\",\"type\":\"string\"}]"; List<MessageargumentList> messageargumentListList= new ArrayList<>(); MessageargumentList messageargumentList = new MessageargumentList(); messageargumentList.setRole("repeated"); messageargumentList.setTag("1"); messageargumentList.setType("string"); MessageargumentList messageargumentList2 = new MessageargumentList(); messageargumentList2.setRole("repeated"); messageargumentList2.setTag("2"); messageargumentList2.setType("string"); messageargumentListList.add(messageargumentList); messageargumentListList.add(messageargumentList2); String pp = new Gson().toJson(messageargumentListList); // System.out.println("****************** "+ pp); // JsonArray jsonArray = new JsonArray(); // jsonArray.add(pp); String r = URLEncoder.encode(pp, "UTF-8"); // System.out.println("******************after encode "+ r); restSolutionMockMvc.perform(get("/api/solutions/matchingModels?&userId="+DEFAULT_AUTHOR_LOGIN+"&portType=" +configurationProperties.getMatchingInputPortType()+"&protobufJsonString="+r)) .andExpect(status().isOk()); }
Example #3
Source File: CookiesUtil.java From opscenter with Apache License 2.0 | 6 votes |
/** * 保存cookies * @param response * @param name * @param value * @param time * @return HttpServletResponse */ public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value,int expiry) { // new一个Cookie对象,键值对为参数 Cookie cookie = new Cookie(name, value); // tomcat下多应用共享 cookie.setPath("/"); cookie.setHttpOnly(true); cookie.setMaxAge(expiry); // 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码 try { URLEncoder.encode(value, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 将Cookie添加到Response中,使之生效 response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie return response; }
Example #4
Source File: GuiHypixelGuild.java From The-5zig-Mod with GNU General Public License v3.0 | 6 votes |
private void findGuild(String name, boolean byPlayerName) { updateStatus(I18n.translate("server.hypixel.loading")); if (byPlayerName) { The5zigMod.getMojangAPIManager().resolveUUID(name, new ExceptionCallback<String>() { @Override public void call(String uuid, Throwable throwable) { findGuild("byUuid=" + uuid); } }); } else { try { findGuild("byName=" + URLEncoder.encode(name, "UTF-8")); } catch (UnsupportedEncodingException e) { updateStatus(e.getMessage()); } } }
Example #5
Source File: ScriptHelper.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
public String urlEncode(final String input) { /* * ************************************************** * IMPORTANT IMPORTANT IMPORTANT IMPORTANT * ************************************************** * * DO NOT REMOVE METHOD OR CHANGE SIGNATURE!!! */ try { return URLEncoder.encode(input, "UTF-8"); } catch (final Exception e) { return ""; } }
Example #6
Source File: AppConfiguration.java From ms-identity-java-webapp with MIT License | 6 votes |
@Override public void configure(HttpSecurity http) throws Exception { String logoutUrl = env.getProperty("endSessionEndpoint") + "?post_logout_redirect_uri=" + URLEncoder.encode(env.getProperty("homePage"), "UTF-8"); http.antMatcher("/**") .authorizeRequests() .antMatchers("/", "/login**", "/error**") .permitAll() .anyRequest() .authenticated() .and() .logout() .deleteCookies() .invalidateHttpSession(true) .logoutSuccessUrl(logoutUrl); }
Example #7
Source File: DetaDBUtil.java From Deta_Cache with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") public static String DBRequest(String request) throws IOException { URL url = new URL("http://localhost:3306/" + URLEncoder.encode(request)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()),"UTF-8")); String out = ""; String out1; while ((out1 = br.readLine()) != null) { out += out1; } conn.disconnect(); return out; }
Example #8
Source File: ResetPasswordRESTHandler.java From arcusplatform with Apache License 2.0 | 6 votes |
private FullHttpResponse login(String email, String password, ChannelHandlerContext ctx) throws Exception { FullHttpRequest fakeLogin = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login"); fakeLogin.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); String params = new StringBuilder("password=") .append(URLEncoder.encode(password, CharsetUtil.UTF_8.name())) .append("&") .append("user=") .append(URLEncoder.encode(email, CharsetUtil.UTF_8.name())) .toString(); ByteBuf buffer = Unpooled.copiedBuffer(params, CharsetUtil.UTF_8); fakeLogin.headers().add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes()); fakeLogin.content().clear().writeBytes(buffer); return authenticator.authenticateRequest(ctx.channel(), fakeLogin); }
Example #9
Source File: WechatServiceImpl.java From cloud-service with MIT License | 6 votes |
@Override public String getWechatAuthorizeUrl(String app, HttpServletRequest request, String toUrl) throws UnsupportedEncodingException { log.info("引导到授权页:{},{}", app, toUrl); WechatInfo wechatInfo = getWechatInfo(app); // 网关域名(外网)加路由到用户系统的规则 https://xxx.xxx.xxx/api-u String domain = wechatConfig.getDomain(); StringBuilder redirectUri = new StringBuilder(domain + "/wechat/" + app + "/back"); if (StringUtils.isNoneBlank(toUrl)) { toUrl = URLEncoder.encode(toUrl, "utf-8"); redirectUri.append("?toUrl=").append(toUrl); } String redirect_uri = URLEncoder.encode(redirectUri.toString(), "utf-8"); // 生成一个随机串,微信再跳回来的时候,会原封不动给我们带过来,到时候做一下校验 String state = UUID.randomUUID().toString(); request.getSession().setAttribute(STATE_WECHAT, state); return String.format(WECHAT_AUTHORIZE_URL, wechatInfo.getAppid(), redirect_uri, state); }
Example #10
Source File: RuleEngineService.java From WeEvent with Apache License 2.0 | 6 votes |
public boolean checkProcessorExist(HttpServletRequest request) { try { String payload = "{\"a\":\"1\",\"b\":\"test\",\"c\":\"10\"}"; String condition = "\"c<100\""; String url = new StringBuffer(this.getProcessorUrl()).append(ConstantProperties.PROCESSOR_CHECK_WHERE_CONDITION) .append(ConstantProperties.QUESTION_MARK).append("payload=").append(URLEncoder.encode(payload, "UTF-8")) .append("&condition=").append(URLEncoder.encode(condition, "UTF-8")) .toString(); CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url); int statusCode = closeResponse.getStatusLine().getStatusCode(); return 200 == statusCode; } catch (Exception e) { return false; } }
Example #11
Source File: RestNLPPortImpl.java From DETA_BackEnd with Apache License 2.0 | 6 votes |
public static Map<String, Object> dataCX(Analyzer analyzer, String string) throws UnsupportedEncodingException { System.out.println(string); Map<String, String> pos = analyzer.getPosCnToCn(); List<String> sets = analyzer.parserString(string); Iterator<String> iterator = sets.iterator(); String cx = ""; while(iterator.hasNext()) { String token = iterator.next(); if(pos.containsKey(token)) { cx += token + "/"+pos.get(token)+" "; } } Map<String, Object> outputMap = new HashMap<>(); outputMap.put(URLEncoder.encode("cx","UTF-8"), URLEncoder.encode(cx,"UTF-8")); return outputMap; }
Example #12
Source File: SPARQLServiceTestCase.java From micro-integrator with Apache License 2.0 | 6 votes |
private boolean isExternalEndpointAvailable() throws IOException { HttpClient httpClient = new DefaultHttpClient(); String url = "http://semantic.eea.europa.eu/sparql?query="; String query = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX cr:<http://cr.eionet.europa.eu/ontologies/contreg.rdf#>\n" + "SELECT * WHERE { ?bookmark a cr:SparqlBookmark;rdfs:label ?label} LIMIT 50"; url = url + URLEncoder.encode(query, "UTF-8"); HttpGet httpGet = new HttpGet(url); httpClient.getParams().setParameter("http.socket.timeout", 300000); httpGet.setHeader("Accept", "text/xml"); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { return true; } return false; }
Example #13
Source File: MySqlConnectionFactoryProviderTest.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
@Test void invalidUrl() { assertThat(assertThrows( IllegalArgumentException.class, () -> ConnectionFactories.get("r2dbcs:mysql://root@localhost:3306?" + "unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8"))).getMessage()) .contains("sslMode"); for (SslMode mode : SslMode.values()) { if (mode.startSsl()) { assertThat(assertThrows( IllegalArgumentException.class, () -> ConnectionFactories.get("r2dbc:mysql://root@localhost:3306?" + "unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8") + "&sslMode=" + mode.name().toLowerCase())).getMessage()) .contains("sslMode"); } } }
Example #14
Source File: HFileOutputFormat3.java From kylin-on-parquet-v2 with Apache License 2.0 | 6 votes |
/** * Serialize column family to data block encoding map to configuration. * Invoked while configuring the MR job for incremental load. * * @param table to read the properties from * @param conf to persist serialized values into * @throws IOException * on failure to read column family descriptors */ @VisibleForTesting static void configureDataBlockEncoding(HTableDescriptor tableDescriptor, Configuration conf) throws UnsupportedEncodingException { if (tableDescriptor == null) { // could happen with mock table instance return; } StringBuilder dataBlockEncodingConfigValue = new StringBuilder(); Collection<HColumnDescriptor> families = tableDescriptor.getFamilies(); int i = 0; for (HColumnDescriptor familyDescriptor : families) { if (i++ > 0) { dataBlockEncodingConfigValue.append('&'); } dataBlockEncodingConfigValue.append(URLEncoder.encode(familyDescriptor.getNameAsString(), "UTF-8")); dataBlockEncodingConfigValue.append('='); DataBlockEncoding encoding = familyDescriptor.getDataBlockEncoding(); if (encoding == null) { encoding = DataBlockEncoding.NONE; } dataBlockEncodingConfigValue.append(URLEncoder.encode(encoding.toString(), "UTF-8")); } conf.set(DATABLOCK_ENCODING_FAMILIES_CONF_KEY, dataBlockEncodingConfigValue.toString()); }
Example #15
Source File: Http.java From litchi with Apache License 2.0 | 6 votes |
public static String concatUrl(String url, Map<String, String> data) { if (data == null) { return url; } try { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : data.entrySet()) { sb.append("&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8")); } if (sb.length() < 1) { return url; } String prefix = sb.substring(1).toString(); if (url.indexOf("?") < 1) { url += "?"; } return url + prefix; } catch (Exception ex) { LOGGER.warn("{}", ex); } return url; }
Example #16
Source File: FavListUrlBuilder.java From MHViewer with Apache License 2.0 | 6 votes |
public String build() { UrlBuilder ub = new UrlBuilder(EhUrl.getFavoritesUrl()); if (isValidFavCat(mFavCat)) { ub.addQuery("favcat", Integer.toString(mFavCat)); } else if (mFavCat == FAV_CAT_ALL) { ub.addQuery("favcat", "all"); } if (!TextUtils.isEmpty(mKeyword)) { try { ub.addQuery("f_search", URLEncoder.encode(mKeyword, "UTF-8")); // Name ub.addQuery("sn", "on"); // Tags ub.addQuery("st", "on"); // Note ub.addQuery("sf", "on"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Can't URLEncoder.encode " + mKeyword); } } if (mIndex > 0) { ub.addQuery("page", Integer.toString(mIndex)); } return ub.build(); }
Example #17
Source File: FormParams.java From verano-http with MIT License | 6 votes |
@Override public final String asString() { return new UncheckedText( new JoinedText( "&", new Mapped<>( input -> String.format( "%s=%s", input.key(), URLEncoder.encode( input.value(), "UTF-8" ) ), new Mapped<>( in -> new KvpOf(in.key().substring(2), in.value()), new Filtered<>( input -> input.key().startsWith("f."), this.dict ) ) ) ) ).asString(); }
Example #18
Source File: MySqlConnectionFactoryProviderTest.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
@Test void validUrl() throws UnsupportedEncodingException { assertThat(ConnectionFactories.get("r2dbc:mysql://root@localhost:3306")).isExactlyInstanceOf(MySqlConnectionFactory.class); assertThat(ConnectionFactories.get("r2dbcs:mysql://root@localhost:3306")).isExactlyInstanceOf(MySqlConnectionFactory.class); assertThat(ConnectionFactories.get("r2dbc:mysql://root@localhost:3306?unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8"))) .isExactlyInstanceOf(MySqlConnectionFactory.class); assertThat(ConnectionFactories.get("r2dbcs:mysql://root@localhost:3306?" + "unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8") + "&sslMode=disabled")).isNotNull(); assertThat(ConnectionFactories.get( "r2dbcs:mysql://root:[email protected]:3306/r2dbc?" + "zeroDate=use_round&" + "sslMode=verify_identity&" + "serverPreparing=true" + String.format("tlsVersion=%s&", URLEncoder.encode("TLSv1.1,TLSv1.2,TLSv1.3", "UTF-8")) + String.format("sslCa=%s&", URLEncoder.encode("/path/to/ca.pem", "UTF-8")) + String.format("sslKey=%s&", URLEncoder.encode("/path/to/client-key.pem", "UTF-8")) + String.format("sslCert=%s&", URLEncoder.encode("/path/to/client-cert.pem", "UTF-8")) + "sslKeyPassword=ssl123456" )).isExactlyInstanceOf(MySqlConnectionFactory.class); }
Example #19
Source File: VideosResource.java From hmdm-server with Apache License 2.0 | 6 votes |
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadVideo(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) throws Exception { File videoDir = new File(this.videoDirectory); if (!videoDir.exists()) { videoDir.mkdirs(); } File uploadFile = new File(videoDir.getAbsolutePath(), fileDetail.getFileName()); writeToFile(uploadedInputStream, uploadFile.getAbsolutePath()); Video video = new Video(); video.setPath(String.format("%s/rest/public/videos/%s", this.baseUrl, URLEncoder.encode(fileDetail.getFileName(), "UTF8"))); return Response.OK(video); }
Example #20
Source File: WxActGoldeneggsVerifyController.java From jeewx-boot with Apache License 2.0 | 6 votes |
/** * 接口获取二维码信息 * @return * @throws UnsupportedEncodingException */ public static com.alibaba.fastjson.JSONObject getScanCodeList() throws UnsupportedEncodingException { PropertiesUtil util = new PropertiesUtil("jeewx.properties"); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("weixinId", util.readProperty("weixinId")); paramMap.put("channel", util.readProperty("channel")); paramMap.put("sceneId", util.readProperty("sceneId")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); Date afterDate = new Date(now.getTime() + 60000); Date beforeDate = new Date(now.getTime() - 120000); paramMap.put("fromDate", sdf.format(beforeDate)); paramMap.put("endDate", sdf.format(afterDate)); String sign = SignatureUtil.sign(paramMap, util.readProperty("scanRecordKey")); String h = util.readProperty("validCodeUrl")+"&weixinId="+util.readProperty("weixinId")+"&channel="+util.readProperty("channel")+"&sceneId="+util.readProperty("sceneId")+"&fromDate="+URLEncoder.encode(sdf.format(beforeDate),"utf-8")+"&endDate="+URLEncoder.encode(sdf.format(afterDate),"utf-8")+"&signature="+sign; com.alibaba.fastjson.JSONObject object = WeiXinHttpUtil.sendGet(h); return object; }
Example #21
Source File: FileServiceQiNiuYun.java From smart-admin with MIT License | 6 votes |
@Override public ResponseDTO<String> getFileUrl(String path) { OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class); try { if (! ossConfig.toString().equals(accessConfig)) { //accessKeyId 发生变动自动重新创建新的UploadManager ossClient = new UploadManager(new Configuration()); token = Auth.create(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()). uploadToken(ossConfig.getBucketName()); accessConfig = ossConfig.toString(); } String encodedFileName = URLEncoder.encode(path, "utf-8"); String domainOfBucket = ossConfig.getEndpoint(); String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName); String accessKey = ossConfig.getAccessKeyId(); String secretKey = ossConfig.getAccessKeySecret(); Auth auth = Auth.create(accessKey, secretKey); //1小时,可以自定义链接过期时间 long expireInSeconds = 3600; String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds); return ResponseDTO.succData(finalUrl); } catch (Exception e) { log.error("QINIU getFileUrl ERROR : {}", e); } return ResponseDTO.wrap(FileResponseCodeConst.URL_ERROR); }
Example #22
Source File: FileUtils.java From v-mock with MIT License | 6 votes |
/** * 下载文件名重新编码 * * @param request 请求对象 * @param fileName 文件名 * @return 编码后的文件名 */ public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException { final String agent = request.getHeader("USER-AGENT"); String filename = fileName; if (agent.contains(MSIE)) { // IE浏览器 filename = URLEncoder.encode(filename, CharsetUtil.UTF_8); filename = filename.replace("+", " "); } else if (agent.contains(FIREFOX)) { // 火狐浏览器 filename = new String(fileName.getBytes(), CharsetUtil.ISO_8859_1); } else { // 其它浏览器 filename = URLEncoder.encode(filename, CharsetUtil.UTF_8); } return filename; }
Example #23
Source File: StringsExpressionProcessor.java From vividus with Apache License 2.0 | 6 votes |
public StringsExpressionProcessor(ILocationProvider locationProvider) { super(List.of( new UnaryExpressionProcessor("trim", StringUtils::trim), new UnaryExpressionProcessor("toLowerCase", StringUtils::lowerCase), new UnaryExpressionProcessor("toUpperCase", StringUtils::upperCase), new UnaryExpressionProcessor("capitalize", StringUtils::capitalize), new UnaryExpressionProcessor("uncapitalize", StringUtils::uncapitalize), new UnaryExpressionProcessor("generate", input -> generate(locationProvider.getLocale(), input)), new UnaryExpressionProcessor("generateLocalized", generateLocalized()), new UnaryExpressionProcessor("encodeUrl", input -> URLEncoder.encode(input, UTF_8)), new UnaryExpressionProcessor("loadResource", ResourceUtils::loadResource), new UnaryExpressionProcessor("resourceToBase64", input -> Base64.getEncoder() .encodeToString(ResourceUtils.loadResourceAsByteArray(input))), new UnaryExpressionProcessor("decodeFromBase64", input -> new String(Base64.getDecoder() .decode(input.getBytes(UTF_8)), UTF_8)), new UnaryExpressionProcessor("encodeToBase64", input -> new String(Base64.getEncoder() .encode(input.getBytes(UTF_8)), UTF_8)), new UnaryExpressionProcessor("anyOf", StringsExpressionProcessor::anyOf) )); }
Example #24
Source File: HopServer.java From hop with Apache License 2.0 | 5 votes |
public HopServerWorkflowStatus getWorkflowStatus( String workflowName, String serverObjectId, int startLogLineNr ) throws Exception { String xml = execService( GetWorkflowStatusServlet.CONTEXT_PATH + "/?name=" + URLEncoder.encode( workflowName, "UTF-8" ) + "&id=" + Const.NVL( serverObjectId, "" ) + "&xml=Y&from=" + startLogLineNr, true ); return HopServerWorkflowStatus.fromXml( xml ); }
Example #25
Source File: FSUtilities.java From ghidra with Apache License 2.0 | 5 votes |
private static void appendHexEncoded(StringBuilder sb, char c) { if (c < 0x80) { sb.append('%').append(hexdigit[c >> 4]).append(hexdigit[c & 0x0f]); return; } sb.append(URLEncoder.encode("" + c, StandardCharsets.UTF_8)); }
Example #26
Source File: PaginationUtil.java From cubeai with Apache License 2.0 | 5 votes |
public static HttpHeaders generateSearchPaginationHttpHeaders(String query, Page page, String baseUrl) { String escapedQuery; try { escapedQuery = URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } HttpHeaders headers = new HttpHeaders(); headers.add("X-Total-Count", Long.toString(page.getTotalElements())); String link = ""; if ((page.getNumber() + 1) < page.getTotalPages()) { link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + "&query=" + escapedQuery + ">; rel=\"next\","; } // prev link if ((page.getNumber()) > 0) { link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + "&query=" + escapedQuery + ">; rel=\"prev\","; } // last and first link int lastPage = 0; if (page.getTotalPages() > 0) { lastPage = page.getTotalPages() - 1; } link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + "&query=" + escapedQuery + ">; rel=\"last\","; link += "<" + generateUri(baseUrl, 0, page.getSize()) + "&query=" + escapedQuery + ">; rel=\"first\""; headers.add(HttpHeaders.LINK, link); return headers; }
Example #27
Source File: MessageFiller.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
protected AttachmentFiller(ParameterImpl param, ValueGetter getter) { super(param.getIndex()); this.param = param; this.getter = getter; mimeType = param.getBinding().getMimeType(); try { contentIdPart = URLEncoder.encode(param.getPartName(), "UTF-8")+'='; } catch (UnsupportedEncodingException e) { throw new WebServiceException(e); } }
Example #28
Source File: ExcelUtil.java From erp-framework with MIT License | 5 votes |
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { throw new BusinessException("5101", e.getMessage()); } }
Example #29
Source File: TopicService.java From WeEvent with Apache License 2.0 | 5 votes |
public TopicEntity getTopicInfo(Integer brokerId, String topic, String groupId, HttpServletRequest request) throws GovernanceException { BrokerEntity broker = this.brokerService.getBroker(brokerId); if (broker == null) { log.error("get topicInfo failed, brokerId:{}, topic:{}, groupId:{}.", brokerId, topic, groupId); throw new GovernanceException("broker is not exists"); } String url; try { // get event broker url url = new StringBuffer(broker.getBrokerUrl()).append(ConstantProperties.BROKER_REST_STATE).append("?topic=") .append(URLEncoder.encode(topic, "UTF-8")).toString(); if (!StringUtils.isBlank(groupId)) { url = new StringBuffer(url).append("&groupId=").append(groupId).toString(); } } catch (Exception e) { log.error("get topicInfo failed, error:{}", e.getMessage()); throw new GovernanceException(ErrorCode.BROKER_CONNECT_ERROR); } log.info("getTopicInfo url:{}", url); TopicEntity topicEntity = invokeBrokerCGI(request, url, new TypeReference<BaseResponse<TopicEntity>>() { }).getData(); if (topicEntity != null) { // get creator from database List<TopicEntity> creators = topicRepository.findAllByBrokerIdAndGroupIdAndTopicNameInAndDeleteAt(brokerId, groupId, new ArrayList<>(Collections.singletonList(topic)), IsDeleteEnum.NOT_DELETED.getCode()); if (CollectionUtils.isNotEmpty(creators)) { topicEntity.setCreater(creators.get(0).getCreater()); } } return topicEntity; }
Example #30
Source File: UrlParamsBuilder.java From huobi_Java with Apache License 2.0 | 5 votes |
/** * 使用标准URL Encode编码。注意和JDK默认的不同,空格被编码为%20而不是+。 * * @param s String字符串 * @return URL编码后的字符串 */ private static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { throw new HuobiApiException(HuobiApiException.RUNTIME_ERROR, "[URL] UTF-8 encoding not supported!"); } }