URLEncoder 无法翻译空格字符 [英] URLEncoder not able to translate space character

查看:21
本文介绍了URLEncoder 无法翻译空格字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

期待

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

输出:

Hello%20World

(20 是空格的 ASCII 十六进制代码)

(20 is ASCII Hex code for space)

然而,我得到的是:

Hello+World

我是否使用了错误的方法?我应该使用的正确方法是什么?

Am I using the wrong method? What is the correct method I should be using?

推荐答案

这符合预期.URLEncoder 实现了关于如何在 HTML 表单中编码 URL 的 HTML 规范.

This behaves as expected. The URLEncoder implements the HTML Specifications for how to encode URLs in HTML forms.

来自 javadocs:

这个类包含静态方法将字符串转换为应用程序/x-www-form-urlencoded MIME格式.

This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

以及来自 HTML 规范:

application/x-www-form-urlencoded

使用此内容类型提交的表单必须编码如下:

Forms submitted with this content type must be encoded as follows:

  1. 控件名称和值被转义.空格字符被替换通过`+'

您将不得不更换它,例如:

You will have to replace it, e.g.:

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

这篇关于URLEncoder 无法翻译空格字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆