如何在Android中创建一个编码字符串?

huangapple go评论69阅读模式
英文:

how to make an encoded string in Android?

问题

所以我想将我的字符串变成`"abc 123 def"`,变成`"abc%20123%20def"`
这样可以在我的HTTP请求中作为查询参数使用,就像这样:

    https://myBaseUrl.com?parameter=abc%20123%20def"

怎么做呢?

我已经尝试过使用以下代码:

    val myString = "321 pop"
    val enCodedString  = URLEncoder.encode(myString, "utf-8")

但是如果我打印输出,会产生这样的字符串:`"321+pop"`

可以使用Java或Kotlin来实现。
英文:

So I want to make my string like "abc 123 def" to be "abc%20123%20def"
so can use it as query parameter in my http request like this

https://myBaseUrl.com?parameter=abc%20123%20def"

how to do that ?

I have tried using this

val myString = "321 pop"
val enCodedString  = URLEncoder.encode(myString, "utf-8")

but if I print, it will produce string like this "321+pop"

Java or Kotlin are OK

答案1

得分: 0

这是空格字符的预期行为。如果你想要将 + 替换为百分号编码,可以使用以下代码:

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
英文:

That's expected behavior for encoding the space character. If you want to replace the + with the percent encoding, do

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));

huangapple
  • 本文由 发表于 2020年10月10日 12:59:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64290134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定