英文:
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"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论