Java HttpUrlConnection POST请求特殊字符的异常行为 [英] Java HttpUrlConnection POST request special characters strange behavior

查看:171
本文介绍了Java HttpUrlConnection POST请求特殊字符的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HttpURLConnection实现POST请求.这是我的代码:

i'm trying to implements a POST request with HttpURLConnection. This is my code:

private static void call(String body) throws IOException{
    HttpURLConnection con = null;

    con = (HttpURLConnection)new URL("http://127.0.0.1:8080").openConnection();

    con.setRequestProperty("Accept-Charset", "UTF-8");
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
    con.setRequestProperty("Accept", "application/json; charset=utf-8");

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    ...
 }

我将其发布到localhost只是为了用WireShark嗅探它.问题是,当我的 body 是包含'ò''à''è''ç'...我看到的请求具有正确的字符串,这些字符用点替换.

I post it to localhost just to sniff it with WireShark. The problem is that when my body is a string containing characters like 'ò' 'à' 'è' 'ç' ... the request i see has le string correct with those characters replaced by dots.

示例:如果正文为"hèllo!" --->请求正文为" h.llo!"

example: if body is "hèllo!" ---> the request body is "h.llo!"

为了测试,我正在java main中执行上述方法,并且我以这种方式传递了参数:

Just for test i'm executing the above method in java main and i pass the parameter this way:

String pString = "{\"titlè\":\"Hèllo Wòrld!\"}";
String params = new String(pString.getBytes("UTF-8"),"UTF-8");
....
call(body);

这就是我在WireShark中得到的东西:

and this is what i get in WireShark:

POST / HTTP/1.1
Accept-Charset: UTF-8
Content-Type: application/json; charset=utf-8
Accept: application/json; charset=utf-8
User-Agent: Java/1.6.0_43
Host: 127.0.0.1:8080
Connection: keep-alive
Content-Length: 24

{"titl.":"H.llo W.rld!"}

任何帮助将不胜感激.谢谢

Any help would be appreciated. Thank you

推荐答案

Java中的内部字符串表示始终为UTF-16.因此,在第二个示例中, params = new String(pString.getBytes("UTF-8"),"UTF-8"); 将pString转换为具有UTF-8内容的字节数组,然后返回存储在params中的UTF-16.字符串进入或离开VM时,必须完成每种编码.这意味着在您将主体写入流中时,必须设置编码.

The internal string representation in Java is always UTF-16. So in your second example params = new String(pString.getBytes("UTF-8"),"UTF-8"); converts pString to a byte array with UTF-8 content and then back to UTF-16 which is stored in params. Every encoding has to be done when strings enter or leave the VM. That means in your case you have to set the encoding when you write the body to the stream.

wr.write(body.getBytes("UTF-8"));

这篇关于Java HttpUrlConnection POST请求特殊字符的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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