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

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

问题描述

我期待

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

输出:



Hello%20World



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



然而,我得到的是:



Hello + World



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

解决方案

这符合预期。 URLEncoder 实现了HTML规范,以便如何对HTML表单中的URL进行编码。



来自 javadocs


此类包含
的静态方法将字符串转换为
应用程序/ x-www-form-urlencoded MIME
来自 HTML规范


application / x-www-form-urlencoded



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


  1. 控制名称和值被转义。空格字符由'+'替换


您必须更换它,例如:

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


I am expecting

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

to output:

Hello%20World

(20 is ASCII Hex code for space)

However, what I get is:

Hello+World

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

解决方案

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

From the javadocs:

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

and from the HTML Specification:

application/x-www-form-urlencoded

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

  1. Control names and values are escaped. Space characters are replaced by `+'

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天全站免登陆