Java Code Examples for java.net.URLEncoder#encode()

The following examples show how to use java.net.URLEncoder#encode() . 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: Token.java    From onenet-iot-project with MIT License 6 votes vote down vote up
static String assembleToken(String version,
                            String resourceName,
                            String expirationTime,
                            String signatureMethod,
                            String accessKey)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    StringBuilder sb = new StringBuilder();
    String res = URLEncoder.encode(resourceName, "UTF-8");
    String sig = URLEncoder.encode(generatorSignature(version,
            resourceName,
            expirationTime,
            accessKey,
            signatureMethod), "UTF-8");
    sb.append("version=")
            .append(version)
            .append("&res=")
            .append(res)
            .append("&et=")
            .append(expirationTime)
            .append("&method=")
            .append(signatureMethod)
            .append("&sign=")
            .append(sig);
    return sb.toString();
}
 
Example 2
Source File: DetaDBUtil.java    From Deta_Cache with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: FlashMapManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void flashAttributesWithQueryParamsWithSpace() throws Exception {

	String encodedValue = URLEncoder.encode("1 2", "UTF-8");

	FlashMap flashMap = new FlashMap();
	flashMap.put("key", "value");
	flashMap.setTargetRequestPath("/path");
	flashMap.addTargetRequestParam("param", encodedValue);

	this.request.setCharacterEncoding("UTF-8");
	this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response);

	MockHttpServletRequest requestAfterRedirect = new MockHttpServletRequest("GET", "/path");
	requestAfterRedirect.setQueryString("param=" + encodedValue);
	requestAfterRedirect.addParameter("param", "1 2");

	flashMap = this.flashMapManager.retrieveAndUpdate(requestAfterRedirect, new MockHttpServletResponse());
	assertNotNull(flashMap);
	assertEquals(1, flashMap.size());
	assertEquals("value", flashMap.get("key"));
}
 
Example 4
Source File: StandardCategoryURLGenerator.java    From openstock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a URL for a particular item within a series.
 *
 * @param dataset  the dataset.
 * @param series  the series index (zero-based).
 * @param category  the category index (zero-based).
 *
 * @return The generated URL.
 */
@Override
public String generateURL(CategoryDataset dataset, int series, 
        int category) {
    String url = this.prefix;
    Comparable seriesKey = dataset.getRowKey(series);
    Comparable categoryKey = dataset.getColumnKey(category);
    boolean firstParameter = !url.contains("?");
    url += firstParameter ? "?" : "&";
    try {
        url += this.seriesParameterName + "=" + URLEncoder.encode(
                seriesKey.toString(), "UTF-8");
        url += "&" + this.categoryParameterName + "="
                + URLEncoder.encode(categoryKey.toString(), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex); // this won't happen :)
    }
    return url;
}
 
Example 5
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String addMtomAttachment(DataHandler dataHandler, String elementNamespace, String elementLocalName) {
	String host = getHost(elementNamespace, dataHandler);
	String contentId = UUID.randomUUID() + "@" + host;
	this.mimeContainer.addAttachment("<" + contentId + ">", dataHandler);
	try {
		contentId = URLEncoder.encode(contentId, "UTF-8");
	}
	catch (UnsupportedEncodingException ex) {
		// ignore
	}
	return CID + contentId;
}
 
Example 6
Source File: ElasticSearchClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Function to search and acquire log entries published from wso2carbon log
 *
 * @param logSnippet log snippet need to match
 * @return found log hits
 * @throws IOException if an error occurs during the invocation
 */
private JSONObject searchCarbonLogs(String logSnippet) throws IOException {

    String baseUrl = hostName + "/" + deploymentStackID + "-carbonlogs*/_search?q=";
    String queryParam = URLEncoder.encode("\"" + logSnippet + "\"", "UTF-8");
    String searchUrl = baseUrl + queryParam;

    log.info("searchURL:" + searchUrl);
    RESTClient restClient = new RESTClient();
    HttpResponse response = restClient.doGet(searchUrl);

    JSONObject resp = new JSONObject(HTTPUtils.getResponsePayload(response));
    log.info("Response" + resp.toString());
    return resp.getJSONObject("hits");
}
 
Example 7
Source File: HttpPostRequestDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeContentDispositionFieldParameters() throws Exception {

    final String boundary = "74e78d11b0214bdcbc2f86491eeb4902";

    String encoding = "utf-8";
    String filename = "attached_файл.txt";
    String filenameEncoded = URLEncoder.encode(filename, encoding);

    final String body = "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"file\"; filename*=" + encoding + "''" + filenameEncoded + "\r\n" +
      "\r\n" +
      "foo\r\n" +
      "\r\n" +
      "--" + boundary + "--";

    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                                                                  HttpMethod.POST,
                                                                  "http://localhost",
                                                                  Unpooled.wrappedBuffer(body.getBytes()));

    req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);
    assertFalse(decoder.getBodyHttpDatas().isEmpty());
    InterfaceHttpData part1 = decoder.getBodyHttpDatas().get(0);
    assertTrue("the item should be a FileUpload", part1 instanceof FileUpload);
    FileUpload fileUpload = (FileUpload) part1;
    assertEquals("the filename should be decoded", filename, fileUpload.getFilename());
    decoder.destroy();
    req.release();
}
 
Example 8
Source File: GlobalAuthUtils.java    From JustAuth with MIT License 5 votes vote down vote up
/**
 * 编码
 *
 * @param value str
 * @return encode str
 */
public static String urlEncode(String value) {
    if (value == null) {
        return "";
    }
    try {
        String encoded = URLEncoder.encode(value, GlobalAuthUtils.DEFAULT_ENCODING.displayName());
        return encoded.replace("+", "%20").replace("*", "%2A").replace("~", "%7E").replace("/", "%2F");
    } catch (UnsupportedEncodingException e) {
        throw new AuthException("Failed To Encode Uri", e);
    }
}
 
Example 9
Source File: OAuthAuthenticator.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
public static String urlencode(String value) {
    try {
        return URLEncoder.encode(value, "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Unexpected: Encoding utf-8 not supported");
    }
}
 
Example 10
Source File: InboundAuthConfigToApiModel.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
private String buildInboundProtocolGetUrl(String applicationId, String inboundAuthType) {

        String inboundPathComponent;
        switch (inboundAuthType) {
            case (FrameworkConstants.StandardInboundProtocols.SAML2):
                inboundPathComponent = ApplicationManagementConstants.INBOUND_PROTOCOL_SAML_PATH_COMPONENT;
                break;
            case (FrameworkConstants.StandardInboundProtocols.OAUTH2):
                inboundPathComponent = ApplicationManagementConstants.INBOUND_PROTOCOL_OAUTH2_PATH_COMPONENT;
                break;
            case (FrameworkConstants.StandardInboundProtocols.PASSIVE_STS):
                inboundPathComponent = ApplicationManagementConstants.INBOUND_PROTOCOL_PASSIVE_STS_PATH_COMPONENT;
                break;
            case (FrameworkConstants.StandardInboundProtocols.WS_TRUST):
                inboundPathComponent = ApplicationManagementConstants.INBOUND_PROTOCOL_WS_TRUST_PATH_COMPONENT;
                break;
            default:
                try {
                    inboundPathComponent = "/" + URLEncoder.encode(inboundAuthType, StandardCharsets.UTF_8.name());
                } catch (UnsupportedEncodingException e) {
                    throw Utils.buildServerError("Error while building inbound protocol for " +
                            "inboundType: " + inboundAuthType, e);
                }
                break;
        }

        return ContextLoader.buildURIForBody(V1_API_PATH_COMPONENT + APPLICATION_MANAGEMENT_PATH_COMPONENT + "/"
                + applicationId + INBOUND_PROTOCOLS_PATH_COMPONENT + inboundPathComponent).toString();
    }
 
Example 11
Source File: AnalysisDetails.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private static String encode(String original) {
    try {
        return URLEncoder.encode(original, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Standard charset not found in JVM", e);
    }
}
 
Example 12
Source File: ExcelUtil.java    From jeewx-boot with Apache License 2.0 5 votes vote down vote up
/**
    * 
    * @param request
    * @param response
    * @param listUser导出数据集
    * @param pojoClass 导出数据的实体
    * @param title 导出文件名
    * @throws Exception
    */
   public static void exportExcel(HttpServletRequest request,HttpServletResponse response, Collection<?> listUser,Class<?> pojoClass,String title) throws Exception {
   	response.setContentType("application/vnd.ms-excel;charset=utf-8");
   	String fileName = title+".xls";
   	
   	//update-begin-Alex----Date:20180910----for:解决IE浏览器导出时名称乱码问题---
   	String finalFileName = null;
   	String userAgent = request.getHeader("user-agent");

   	if (userAgent != null && userAgent.indexOf("MSIE") >= 0 || userAgent.indexOf("Trident") >= 0 || userAgent.indexOf("Edge") >= 0) {
   		//IE(Trident)内核
   		finalFileName =URLEncoder.encode(fileName,"UTF-8");
   	} else if(userAgent != null && userAgent.indexOf("chrome") >= 0 || userAgent.indexOf("safari") >= 0 || userAgent.indexOf("Firefox") >= 0) {
   		//谷歌、火狐等浏览器
   		finalFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
   	}else{
   		finalFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
   	}
   	//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
   	response.setHeader("Content-Disposition", "attachment; filename="+ finalFileName);
   	//update-end-Alex----Date:20180910----for:解决IE浏览器导出时名称乱码问题---
   	File file = new File(new Date(0).getTime()+".xls");
   	OutputStream outputStream = new FileOutputStream(file);
   	ExcelUtil.exportExcel(title,pojoClass, listUser, outputStream);
   	InputStream is = new BufferedInputStream(new FileInputStream(file.getPath()));
   	file.delete();
   	outputStream.close();
   	OutputStream os = response.getOutputStream();
   	byte[] b = new byte[2048];
   	int length;
   	while ((length = is.read(b)) > 0) {
   		os.write(b, 0, length);
   	}
   	os.close();
   	is.close();
}
 
Example 13
Source File: MessageFiller.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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 14
Source File: StoryEditorActivity.java    From zom-android-matrix with Apache License 2.0 4 votes vote down vote up
private void storeHTML (String html)
{
    // import
    String sessionId = "self";
    String offerId = UUID.randomUUID().toString();

    try {

        String title = mEditTitle.getText().toString();
        if (TextUtils.isEmpty(title))
            title = "story" + new Date().getTime() + ".html";
        else
            title = URLEncoder.encode(title,"UTF-8")  + ".html";

        final Uri vfsUri = SecureMediaStore.createContentPath(sessionId,title);

        OutputStream out = new FileOutputStream(new File(vfsUri.getPath()));
        String mimeType = "text/html";

        out.write(html.getBytes());
        out.flush();
        out.close();

        //adds in an empty message, so it can exist in the gallery and be forwarded
        Imps.insertMessageInDb(
                getContentResolver(), false, new Date().getTime(), true, null, vfsUri.toString(),
                System.currentTimeMillis(), Imps.MessageType.OUTGOING_ENCRYPTED,
                0, offerId, mimeType, null);


        Intent data = new Intent();
        data.setDataAndType(vfsUri,mimeType);
        setResult(RESULT_OK, data);



    }
    catch (IOException ioe)
    {
        Log.e(LOG_TAG,"error importing photo",ioe);
    }
}
 
Example 15
Source File: Translator.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
String translateOutgoing(String message) throws IOException
{
	final String url = outgoingUrlBase + URLEncoder.encode(message, StandardCharsets.UTF_8);
	return translate(new URL(url));
}
 
Example 16
Source File: DefaultAggregator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private static String urlEncode(String input) {
    return URLEncoder.encode(input, StandardCharsets.UTF_8);
}
 
Example 17
Source File: UDIDController.java    From signature with MIT License 4 votes vote down vote up
@ApiOperation(value="/getUDID", notes="获取设备udid", produces = "application/json")
@ApiImplicitParams(value = {
        @ApiImplicitParam(name = "id", value = "IPA id", required = true),
})
@PostMapping("/getUDID")
public void getUDID(HttpServletResponse response, HttpServletRequest request, String id) throws UnsupportedEncodingException {
    response.setContentType("text/html;charset=UTF-8");
    long begin = System.currentTimeMillis();
    String ua = request.getHeader("User-Agent");
    System.out.println("当前时间: " + DateUtil.now() + "\n当前产品id: " + id + "\n当前用户User-Agent: " + ua);
    String itemService = null;
    try {
        request.setCharacterEncoding("UTF-8");
        //获取HTTP请求的输入流
        InputStream is = request.getInputStream();
        //已HTTP请求输入流建立一个BufferedReader对象
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        StringBuilder sb = new StringBuilder();
        //读取HTTP请求内容
        String buffer = null;
        while ((buffer = br.readLine()) != null) {
            sb.append(buffer);
        }
        String xml = sb.toString().substring(sb.toString().indexOf("<?xml"), sb.toString().indexOf("</plist>")+8);
        NSDictionary parse = (NSDictionary) PropertyListParser.parse(xml.getBytes());
        String udid = (String) parse.get("UDID").toJavaObject();
        itemService = analyzeUDID(udid, id);
        System.out.println("itemService文件名为: " + itemService);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String redirect = Config.redirect + "/detail/" + id;
    if (itemService!=null) {
        String encode = "itms-services://?action=download-manifest&url=" + Config.aliTempHost + "/" + itemService;
        redirect += "?itemService=" + URLEncoder.encode(encode, "UTF-8" );
        packageService.updatePackageCountById(Integer.valueOf(id));
    }
    long end = System.currentTimeMillis();
    long result = (end - begin)/1000;
    System.out.println("自动签名执行耗时: " + result + "秒");
    response.setHeader("Location", redirect);
    response.setStatus(301);
}
 
Example 18
Source File: DKSearchOutputImpl.java    From dk-fitting with Apache License 2.0 4 votes vote down vote up
/**
 * 从es导出数据,导出为xls
 * @param hostIps
 * @param clusterName
 * @param indexName
 * @param typeName
 * @param port
 * @param start
 * @param size
 * @return
 * @throws TException
 */
@Override
public String ES2XLS(String hostIps, String clusterName, String indexName, String typeName, int port, int start, int size) throws Exception {
    String type=".xlsx";
    client=ESUtils.getClient( hostIps,port,clusterName );
    IndicesExistsResponse existsResponse = client.admin().indices().prepareExists( indexName ).execute().actionGet();
    if (!existsResponse.isExists()){
        return "index Non-existent ";
    }
    TypesExistsResponse typesExistsResponse = client.admin().indices().prepareTypesExists( indexName ).setTypes( typeName ).execute().actionGet();
    if (!typesExistsResponse.isExists()){
        return "type Non-existent";
    }
    //把导出的数据以json格式写到文件里,
    BufferedOutputStream out=new BufferedOutputStream( new FileOutputStream( indexName+"_"+typeName+"_"+System.currentTimeMillis()+type,true) );
    SearchResponse response=null;

    long totalHits = client.prepareSearch( indexName ).setTypes( typeName ).get().getHits().totalHits;
    //setSearchType(SearchType.Scan) 告诉ES不需要排序只要结果返回即可 setScroll(new TimeValue(600000)) 设置滚动的时间
    //每次返回数据10000条。一直循环查询直到所有的数据都查询出来
    //setTerminateAfter(10000)    //如果达到这个数量,提前终止
    SearchRequestBuilder requestBuilder = client.prepareSearch( indexName ).setTypes( typeName ).setQuery( QueryBuilders.matchAllQuery() ).setScroll( new TimeValue(600000) );
    response=requestBuilder.setFrom( start ).setSize( size ).execute().actionGet();
    String title="ES导出";
    title=URLEncoder.encode( title,"UTF-8" );
    SearchHits searchHits = response.getHits();
    if (searchHits==null){return "no searchHit";}
    String[] keys=null;
    ArrayList<Object[]> list=new ArrayList<>(  );
    for (int i = 0; i <searchHits.getHits().length ; i++) {
        Set<String> keySet = searchHits.getHits()[i].getSource().keySet();
        keys = keySet.toArray( new String[keySet.size()] );
        Collection<Object> values = searchHits.getHits()[i].getSource().values();
        Object[] object = values.toArray( new Object[values.size()] );
        list.add( object );
    }
     ExportExcelUtils.exportExcelXSSF( title, keys, list, out );

    out.close();
    return "SUCCESS";
}
 
Example 19
Source File: KeycloakIdentityProviderSession.java    From camunda-bpm-identity-keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean checkPassword(String userId, String password) {

	// engine can't work without users
	if (StringUtils.isEmpty(userId)) {
		return false;
	}

	// prevent missing/empty passwords - we do not support anonymous login
	if (StringUtils.isEmpty(password)) {
		return false;
	}
	
	// Get Keycloak username for authentication
	String userName;
	try {
		userName = getKeycloakUsername(userId);
	} catch (KeycloakUserNotFoundException aunfe) {
		KeycloakPluginLogger.INSTANCE.userNotFound(userId, aunfe);
		return false;
	}
		
	try {
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED + ";charset=" + keycloakConfiguration.getCharset());
		HttpEntity<String> request = new HttpEntity<>(
	    		"client_id=" + keycloakConfiguration.getClientId()
   	    		+ "&client_secret=" + keycloakConfiguration.getClientSecret()
   	    		+ "&username=" + userName
   	    		+ "&password=" + URLEncoder.encode(password, keycloakConfiguration.getCharset())
   	    		+ "&grant_type=password",
   	    		headers);
		restTemplate.postForEntity(keycloakConfiguration.getKeycloakIssuerUrl() + "/protocol/openid-connect/token", request, String.class);
		return true;
	} catch (HttpClientErrorException hcee) {
		if (hcee.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
			return false;
		}
		throw new IdentityProviderException("Unable to authenticate user at " + keycloakConfiguration.getKeycloakIssuerUrl(),
				hcee);
	} catch (RestClientException rce) {
		throw new IdentityProviderException("Unable to authenticate user at " + keycloakConfiguration.getKeycloakIssuerUrl(),
				rce);
	} catch (UnsupportedEncodingException uee) {
		throw new IdentityProviderException("Unable to authenticate user at " + keycloakConfiguration.getKeycloakIssuerUrl(),
				uee);
	}

}
 
Example 20
Source File: URLUtils.java    From openemm with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Simple wrapper on java.net.URLEncoder. It encodes URLs with UTF-8
 * @param url
 * @return
 * @throws UnsupportedEncodingException
 */
public static String encodeURL(String url) throws UnsupportedEncodingException{
	return URLEncoder.encode(url, "UTF-8");
}