首页 > 代码库 > java项目和C#项目实现通信

java项目和C#项目实现通信

C#端代码:

String contents = this.projectTypeNameTB.Text + "," + this.describeTB.Text;
//请求
string uri = "http://192.168.1.149:8080/zdys/TestServlte";//?action=" + HttpUtility.UrlEncode(testString);
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = "post";//请求方法
request.ProtocolVersion = new Version(1, 1);

// string param = "这是传送给java端的内容:Hello java!";
string param = contents;
byte[] bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream stream = response.GetResponseStream())
{

StreamReader reader = new StreamReader(stream);
string responseString = reader.ReadToEnd();
reader.Close();
MessageBox.Show(responseString);
}

 

java端代码:

/**
* doPost(运用servlet连接elasticsearch‘)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//使用post方法
request.setCharacterEncoding("UTF-8");//设置字符编码
response.setContentType("text/html;charset=utf-8");
//获取流的同时设置编码格式为utf-8(虽然上面已经设置了,但是这边还是要再设一次)
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String lines = reader.readLine();//获取C#端传输过来的数据为
System.out.println("C#端传输过来的数据为:"+lines);//lines = new String(lines.getBytes(), "utf-8");
reader.close();//关闭连接
AddIndexContentServiceImpl aicsi = new AddIndexContentServiceImpl();//new一个添加索引内容接口的实现类
ProjectTypeEntity pte = new ProjectTypeEntity(); //new一个添加索引内容对象的实现类(要和C#端所需数据相对应)
String[] array= StringTools.splitString(lines, 2);//自定义分割传来的字符串获取自己需要的格式
pte.setProjectType(array[0]);
pte.setDescrible(array[1]);
System.out.println(pte.getDescrible()+pte.getProjectType());
String addContent = JsonFieldDataTools.getProjectTypeFieldData(pte);//调用相应的方法拼装字符串
boolean flag=aicsi.addProjectTypeContent("zhongdi", "projectType", addContent);//执行相应的添加索引内容的方法
if(flag){
System.out.println("添加成功");
}
//直接转换为系统默认编码下对应的字符,再输出
PrintWriter out = response.getWriter();
out.println("这是返回给C#端的信息:Hello C#!");
out.flush();
out.close();
//String searchContent = URLDecoder.decode(request.getParameter("action"),"UTF-8");
//ESTools.createIndex(index, indexType);//创建索引和mapping
ESTools.close();
System.out.println("执行完毕");
//response.sendRedirect("zdys/esControl.jsp");

}

java项目和C#项目实现通信