与web服务器通信应先使用postman测试,确认服务器正常再写代码
发送UTF-8 的json字符串
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net; public enum HttpVerb { GET, //method 常用的就这几样,当然你也可以添加其他的 get:获取 post:修改 put:写入 delete:删除 POST, PUT, DELETE } namespace restPostJsonToWebServer { public class restPostJson { public restPostJson() { EndPoint = ""; Method = HttpVerb.GET; ContentType = "text/xml"; PostData = ""; } public restPostJson(string endpoint) { EndPoint = endpoint; Method = HttpVerb.GET; ContentType = "text/xml"; PostData = ""; } public restPostJson(string endpoint, HttpVerb method) { EndPoint = endpoint; Method = method; ContentType = "text/xml"; PostData = ""; } public restPostJson(string endpoint, HttpVerb method, string postData) { EndPoint = endpoint; Method = method; ContentType = "text/xml"; PostData = postData; } public restPostJson(string endpoint, string postData) { EndPoint = endpoint; Method = HttpVerb.POST; ContentType = "application/json"; PostData = postData; } public string restPostJsonToWebServer(string text) { return "I'm restPostJson"; } public string EndPoint { get; set; } //请求的url地址 public HttpVerb Method { get; set; } //请求的方法 public string ContentType { get; set; } //格式类型application/json public string PostData { get; set; } //传送的数据,当然了我使用的是json字符串 public string MakeRequest() { return MakeRequest(""); } public string MakeRequest(string parameters) { var responseValue = string.Empty; var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters); request.Method = Method.ToString(); request.ContentLength = 0; request.ContentType = ContentType; if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)//如果传送的数据不为空,并且方法是post { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("utf-8").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8 request.ContentLength = bytes.Length; try { using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } catch (Exception e) { responseValue = "error,"; responseValue += e.Message; return responseValue; } } if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//如果传送的数据不为空,并且方法是put { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("utf-8").GetBytes(PostData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } try { using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); throw new ApplicationException(message); } // grab the response using (var responseStream = response.GetResponseStream()) { if (responseStream != null) using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } return responseValue; } } catch (Exception e) { //e.Message responseValue = "error,GetResponse异常" + e.Message; return responseValue; } } } }
VC 调用代码
#using "../debug/restPostJsonToWebServer.dll" using namespace restPostJsonToWebServer; CString restJsonToWebSer(CString strHttpAdd, CString strData) { System::String ^sHttpAdd = gcnew System::String(strHttpAdd); System::String ^sdata = gcnew System::String(strData); restPostJson ^myRest = gcnew restPostJson(sHttpAdd, sdata); CString resultGet = myRest->MakeRequest(); return resultGet; }
如果要发送其他类型的字符串
public string HttpPostAsXWWWFormUrlEncoded(string data, string url) { string result = ""; try { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.AllowAutoRedirect = true; request.Timeout = 2 * 1000; request.ContentType = "application/x-www-form-urlencoded"; var byteArray = Encoding.Default.GetBytes(data); request.ContentLength = byteArray.Length; using (var newStream = request.GetRequestStream()) { newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); } var response = (HttpWebResponse)request.GetResponse(); var rspStream = response.GetResponseStream(); using (var reader = new StreamReader(rspStream, Encoding.UTF8)) { result = reader.ReadToEnd(); rspStream.Close(); } response.Close(); } catch (Exception ex) { return ex.Message; } return result; }
如果请求头中要加入数据
public string httpHeadAuthorizationPostJson(string ParameterBody, string url, string Token) { try { byte[] postData = Encoding.UTF8.GetBytes(ParameterBody); WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", "application/json"); //采取POST方式必须加的header string strHead; strHead = "Bearer " + Token; webClient.Headers.Add("Authorization", strHead); //采取POST方式必须加的header webClient.Headers.Add("ContentLength", postData.Length.ToString()); byte[] responseData = webClient.UploadData(url, "POST", postData); //得到返回字符流 string strRes = Encoding.UTF8.GetString(responseData); //解码 return strRes; } catch (AggregateException ex) { MessageBox.Show(ex.Message); return ex.Message; } }
使用WebClient类通信
public string LocalHttpGet() { try { string GetHttpData = ""; string url = "http://127.0.0.1/api/HeartbeatV1"; WebClient client = new WebClient(); byte[] data = client.DownloadData(url); GetHttpData = Encoding.UTF8.GetString(data); return GetHttpData; } catch (Exception ex) { return ex.Message; } }
使用WebClient加一些参数
public string LocalHttpPost(string PostData) { try { string url = "http://127.0.0.1/api/TestDetailV1Contriller"; // api路径(请求接口) byte[] postData = Encoding.UTF8.GetBytes(PostData); WebClient webClient = new WebClient(); webClient.Headers.Add("accept", "text/plain"); webClient.Headers.Add("Content-Type", "application/json"); //采取POST方式必须加的header webClient.Headers.Add("ContentLength", postData.Length.ToString()); byte[] responseData = webClient.UploadData(url, "POST", postData); //得到返回字符流 string strRes = Encoding.UTF8.GetString(responseData); //解码 return strRes; } catch (Exception ex) { return ex.Message; } }
标签:WEB,return,string,C#,request,using,var,服务器,public From: https://www.cnblogs.com/ckrgd/p/17012045.html