乐闻世界logo
搜索文章和话题

How to do url encoding for query parameters in Kotlin

1个答案

1

In Kotlin, URL-encoding query parameters is a common requirement, especially when handling Web API requests. URL encoding ensures that URLs are valid and can be transmitted correctly over the internet. In Kotlin, we can use Java's standard library URLEncoder for encoding. Here is a specific example:

kotlin
import java.net.URLEncoder import java.nio.charset.StandardCharsets fun encodeQueryParam(param: String): String { return URLEncoder.encode(param, StandardCharsets.UTF_8.toString()) } fun main() { val originalParam = "这是一个测试!@#¥%……&*()" val encodedParam = encodeQueryParam(originalParam) println("原始参数: $originalParam") println("编码后的参数: $encodedParam") }

In this example:

  1. We first import java.net.URLEncoder and java.nio.charset.StandardCharsets.
  2. We define an encodeQueryParam function that accepts a string parameter and returns the encoded string. Here, we use the URLEncoder.encode method, which requires two parameters: the string to encode and the character set.
  3. In the main function, we create an original query parameter originalParam, call encodeQueryParam to encode it, and finally print the original and encoded parameters.

This ensures that parameters passed to the Web API are safe and valid, avoiding issues caused by special characters.

2024年6月29日 12:07 回复

你的答案