C#调用Java后端的restful接口(传递多参数)

由于工作中的需要,在C#的winform窗口中调用html前端页面(是用webbrowser实现,此处不多做概述),但是前端请求的接口是用Java编写的,在webbrowser中使用C#来请求Java后端的restful接口。

此处是C# winform窗口中请求的部分

	void addCollection(object sender, HtmlElementEventArgs e)
	{
	
	HtmlElement a = (HtmlElement)sender;
	int value = int.Parse(a.GetAttribute("id"));
	
	String url = "http://localhost:8080/collect/add";
	HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
	request.Method = "POST";
	request.ContentType = "application/json";
	
	//创建参数
	FileBO fileBo = new FileBO();
	fileBo.fileId = value;
	fileBo.userId = Authentication.USERID;
	byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileBo));
	using (Stream reqStream = request.GetRequestStream())
	{
	  reqStream.Write(data, 0, data.Length);
	  reqStream.Close();
	}
	HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
	Stream stream = resp.GetResponseStream();
	//获取响应内容
	using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
	{
	   MessageBox.Show(reader.ReadToEnd()+"");
	}
	
	}

多个参数的传递主要是建一个实体类,然后将对象序列化为字节流

    class FileBO
    {
        public int fileId { get; set; }
        public string userId { get; set; }

    }

此处是调用Java的另一个接口

String url = "http://localhost:8080/collect/showAll";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
//创建参数

CollectBO collectBO = new CollectBO();
collectBO.userId = Authentication.USERID;
collectBO.currentPage = 1;
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(collectBO));
using (Stream reqStream = request.GetRequestStream())
{
    reqStream.Write(data, 0, data.Length);
    reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
Object result = null;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
    result = reader.ReadToEnd();
}
if(result != null)
{
    MessageBox.Show(result.ToString());
}

你可能感兴趣的:(c#,ajax,restful)