发送HttpGet请求时,URL包含空格怎么办?

books1958 2013-07-24 04:09:46
做一个项目,需要将用户的留言信息上传至服务器。
我使用的是HttpGet请求,将留言内容直接拼接在url上面的。
可是,当留言内容中间出现空格时,执行HttpGet get = new HttpGet(url)语句时会抛异常:IllegalArgumentException
请教各位大神,这个怎么办啊?
...全文
51903 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
hety163 2014-10-28
  • 打赏
  • 举报
回复
不对啊,用URLEncode.encode("hello world!", "UTF-8");之后的结果是hello+world啊,而不是hello%20world啊 有人知道怎么做才正确么,不用replaceall的话(感觉不太科学啊)
  • 打赏
  • 举报
回复
在执行之前写上 url = url.replaceAll(" ", "%20"); 把空格替换掉
antsoftware 2013-11-28
  • 打赏
  • 举报
回复
8 楼 正解.....解决了我的问题 赞.
books1958 2013-07-31
  • 打赏
  • 举报
回复
引用 9 楼 woshilisao 的回复:
为什么不用post?get的url有长度的限制,接不了多少字
php的提供的是get
books1958 2013-07-31
  • 打赏
  • 举报
回复
引用 7 楼 sasuke38 的回复:
我都说了 是处理指定参数 文字的意思很明白了 只能用来处理参数 最好是只处理可能出现空格的参数
嗯,明白了,就是这样写稍微有点复杂~~多谢了!
woyaowenzi 2013-07-26
  • 打赏
  • 举报
回复
上面都已说得很明白了。
woshilisao 2013-07-26
  • 打赏
  • 举报
回复
为什么不用post?get的url有长度的限制,接不了多少字
Jobernowl 2013-07-26
  • 打赏
  • 举报
回复
引用 7 楼 sasuke38 的回复:
我都说了 是处理指定参数 文字的意思很明白了 只能用来处理参数 最好是只处理可能出现空格的参数
比如 http://baidu.com?name=han&content=hello world则这样处理 url = “http://baidu.com?name=han&content=”+URLEncoder.encode(“hello world”,“utf-8”);
Jobernowl 2013-07-26
  • 打赏
  • 举报
回复
我都说了 是处理指定参数 文字的意思很明白了 只能用来处理参数 最好是只处理可能出现空格的参数
berdy 2013-07-25
  • 打赏
  • 举报
回复
HttpGet get = new HttpGet(URLEncoder.encode(url,"UTF-8"));
黄小楼 2013-07-25
  • 打赏
  • 举报
回复
decode啊
yoxibaga 2013-07-25
  • 打赏
  • 举报
回复
URLEncoder.encode().这个方法把所有非字母数字字符改变为%序列(除了空格、下划线、连字符、点和星号),如果把整个url给encode的话,=,&这些字符也会编码。所以最好逐部分编码。

String query = URLEncode.encode("name");
query += "=";
query += URLEncode.encode("han");
query += "&";
query += URLEncode.encode("content");
query += "=";
query += URLEncode.encode("hello world");

String url = "http://baidu.com?"+query;
Jobernowl 2013-07-25
  • 打赏
  • 举报
回复
url不可能出现空格那看来是参数出现空格 可以使用URLEncoder.encode来处理指定参数
books1958 2013-07-25
  • 打赏
  • 举报
回复
自己顶一下!
books1958 2013-07-25
  • 打赏
  • 举报
回复
引用 2 楼 sasuke38 的回复:
url不可能出现空格那看来是参数出现空格 可以使用URLEncoder.encode来处理指定参数
该怎么Encode呢?是把整个url都放进去吗?我刚才试了一下,大概是这样的: (为了保密,我把网址换成了baidu)

String url="http://baidu.com?name=han&content=hello world";
HttpGet get = new HttpGet(URLEncoder.encode(url,"UTF-8"));
然后报异常了: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://baidu.com?name=han&content=hello world 是不是不应该把整个url给Encode了啊?如果只Encode后面的请求语句的话,再怎么和前面的http://baidu.com拼在一起呢?

80,348

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧