服务器端 接受中文 希望为 utf - 8,但是我发送的http方法 英文数字都为utf-8,只有中文在服务器端就变为了GBK,如何让中文参数在服务器端编码也为utf-8? http方法如下
/**
* POST请求,字符串形式数据
*
* @param url
* 请求地址
* @param param
* 请求数据
* @param charset
* 编码方式
*/
public static String sendPostUrl(String url, String param, String charset) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(new String (param.getBytes(), "UTF-8"));
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
我在本地弄个服务器端 测试,发现这个方法 传输英文数字,服务器端接受参数编码为utf-8,参数为中文编码就为GBK了,请问是这个http方法有问题吗?能否让中文参数编码在服务器端编码也为utf-8
传输前先转码,然后服务端接受后再解码URLEncoder.encode()
需要在服务端处理时设置编码方式UTF-8啊,你看看你们服务端是不是设置GBK了
URLEncoder.encode() 转成和服务端 一样 就行了
一般编译器里都可以设置编码格式的,你将所有需要用的的地方设置UTF-8
这个一定要服务端设定,你这里怎么想办法也解决不了
List list = new List();
string pattern = @"^[\u300a\u300b]|[\u4e00-\u9fa5]|[\uFF00-\uFFEF]";
if (System.Text.RegularExpressions.Regex.IsMatch(data, pattern))
{
//获取中文集合
System.Text.RegularExpressions.Match m =
System.Text.RegularExpressions.Regex.Match(data, pattern);
while (m.Success)
{
list.Add(m.Groups[0].Value);
m = m.NextMatch();
}
foreach (var str in list)
{
data = data.Replace(str, System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8));
}
}
这是C#上我做的处理方式,中文要转码,你换成对应语言就好了
原文地址:https://blog.csdn.net/tlms_/article/details/78749980
上文完美的解决了你的问题,但是他说不能复制,会被删除,所以你自己去看吧。