因為工作需要調用WebService介面,查了下資料,發現添加服務引用可以直接調用websevice 參考地址:https://www.cnblogs.com/peterpc/p/4628441.html 如果不添加服務引用又怎麼做呢?於是又去查看怎麼根據http協議調用webservice並做了個 ...
因為工作需要調用WebService介面,查了下資料,發現添加服務引用可以直接調用websevice
參考地址:https://www.cnblogs.com/peterpc/p/4628441.html
如果不添加服務引用又怎麼做呢?於是又去查看怎麼根據http協議調用webservice並做了個無參介面測試,如下:
但一做有參的介面調用就提示500錯誤(遠程伺服器返回錯誤(500)內部伺服器錯誤),查了半天資料,大多數都說是ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 改成ContentType = "text/html";或者在<@Page..%>中設置 ValidateRequest="false" 即可(這裡無需修改Content-type)。結果還是報一樣的錯誤。最後再https://www.jb51.net/article/120015.htm中發現參數是要拼接一下的 (param = HttpUtility.UrlEncode(
"param1"
) +
"="
+ HttpUtility.UrlEncode(num1) +
"&"
+ HttpUtility.UrlEncode(
"param2"
) +
"="
+ HttpUtility.UrlEncode(num2);
) ,這樣傳遞int、string類型的參數都沒問題。業務要求傳遞的是圖片二進位轉化的string類型數據,結果還是報500錯誤。經過調試對比發現圖片二進位數據轉化成的string類型數據沒有根據url形式傳遞,而是帶有特殊符號的,知道問題所在就好辦了,把它轉化成有效的url傳輸數據就行,.net也有現成的封裝方法:HttpServerUtility.UrlTokenEncode(bmpBytes),這樣500錯誤也解決了。
測試代碼如下:
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 Bitmap bmp = new Bitmap(System.Drawing.Image.FromFile("C:/Users/TYTD/Desktop/測試樣本/ch_DJI_279.jpg")); 4 MemoryStream ms = new MemoryStream(); 5 bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 6 ms.Flush(); 7 //將二進位數據存到byte數組中 8 byte[] bmpBytes1 = ms.ToArray(); 9 bmp.Dispose(); 10 11 string bmpBytes = HttpUtility.UrlEncode("bmpBytes") + "=" + HttpServerUtility.UrlTokenEncode(bmpBytes1); 12 13 string url = "http://192.168.0.28:9800/WebService1.asmx/Send_Image"; 14 string a = CallServiceByGet1(url, bmpBytes); 15 16 } 17 public static string CallServiceByGet1(string strURL,string a) 18 { 19 var result = string.Empty; 20 //創建一個HTTP請求 21 byte[] byt = Encoding.UTF8.GetBytes(a); 22 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL); 23 request.Method = "POST"; 24 request.ContentType = "application/x-www-form-urlencoded"; 25 request.ContentLength = byt.Length; 26 27 request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 28 System.IO.Stream outputStream = request.GetRequestStream(); 29 outputStream.Write(byt, 0, byt.Length); 30 outputStream.Close(); 31 32 HttpWebResponse response; 33 Stream responseStream; 34 StreamReader reader; 35 string srcString; 36 try 37 { 38 response = (HttpWebResponse)request.GetResponse();//獲取http請求的響應對象 39 } 40 catch (WebException ex) 41 { 42 return ex.Message; 43 } 44 responseStream = response.GetResponseStream(); 45 reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); 46 srcString = reader.ReadToEnd(); 47 result = srcString; //返回值賦值 48 reader.Close(); 49 50 return result; 51 }