最近在做数据收集的项目时使用到C#编写客户端,将数据发送到java后台接收后进行处理,遇到了一些坑,同时也一步一步解决,上代码。
C#端:
String strDis = "{\"data\":[{\"name\":\"zhangsan\",\"age\":66}]}";
String strData = "{\"data\":[{\"name\":\"lisi\",\"age\":33}]}";
strData = strData.Replace("&", "%26");
strDis = strDis.Replace("%", "MMMMM");
strDis = strDis.Replace("&", "%26");
Uri url = new Uri("http://localhost:8888/online/postData");
WebRequest webRequest = WebRequest.Create(url);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.Timeout = 5000;
using (Stream requestStream = webRequest.GetRequestStream())
{
byte[] paramByte = Encoding.UTF8.GetBytes("user1=" + strDis + "&user2=" + strData);
requestStream.Write(paramByte, 0, paramByte.Length);
}
WebResponse webResponse = webRequest.GetResponse();
using (StreamReader myStream = new StreamReader(webResponse.GetResponseStream()))
{
MessageBox.Show(myStream.ReadToEnd());
}
通过组建的Json字符串和WebRequest 将数据发送到后台(客户端和服务器要可以通信喲。。。)
Java后台,我使用的是SpringBoot:
@RequestMapping(value="postData",method=RequestMethod.POST)
@ResponseBody
public String getPostData( HttpServletResponse response,
HttpServletRequest request) throws UnsupportedEncodingException {
String strUser1 = request.getParameter("user1");
String strUser2 = request.getParameter("user2");
// 中文存在乱码需要转码
String decodedToUTF8 = new String(strUser1.getBytes("ISO-8859-1"), "GBK");
String decodedToUTF81 = new String(strUser2.getBytes("ISO-8859-1"), "GBK");
// 如果需要使用fastjson转化对象,需要将其中的反斜杠"\"替换掉, 不知道高版本的fastjson有没有解决该问题
strUser1 = strUser1.replaceAll("\\\\","ttttt");
strUser2 = strUser2.replaceAll("\\\\","ttttt");
User user1 = JSON.parseObject(strUser1,User.class);
User user2 = JSON.parseObject(strUser2,User.class);
// 后面需要把前面替换的字符替换回来。。。。。
return "success";
}
后台接收后组建对象。
-
在发送数据时要将“&" 转换为“%26”,特殊转义字符。
-
发送的字符中如果含有“%”,要替换为其他字符,否则可能导致发送不成功。
-
中文乱码问题,C#端解决(我这边是ISO-8859-1,其他的编码方式更加容易),转换为GBK
-
string Message = "HID(ÈË»ú½Ó¿ÚÉ豸)"; Encoding ISO88591Encoding = Encoding.GetEncoding("ISO-8859-1"); Encoding GB2312Encoding = Encoding.GetEncoding("GBK"); //这个地方很特殊,必须利用GB2312编码 byte[] srcBytes = ISO88591Encoding.GetBytes(Message); //将原本存储ISO-8859-1的字节数组当成GB2312转换成目标编码(关键步骤) byte[] dstBytes = Encoding.Convert(GB2312Encoding, Encoding.Default, srcBytes); char[] dstChars = new char[Encoding.Default.GetCharCount(dstBytes, 0, dstBytes.Length)]; Encoding.Default.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);//利用char数组存储字符 string sResult = new string(dstChars);
5. JAVA端转化:
String encodedWithISO88591 = "HID(ÈË»ú½Ó¿ÚÉ豸)";
String decodedToUTF8 = new String(encodedWithISO88591.getBytes("ISO-8859-1"), "GBK");
一个简单的C#post数据Java接收数据的示例就完成了,本示例是带参数的发送数据,也可以通过发送文件的方式进行。
欢迎关注公众号