(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误

因为工作需要调用WebService接口,查了下资料,发现添加服务引用可以直接调用websevice

参考地址:https://www.cnblogs.com/peterpc/p/4628441.html

如果不添加服务引用又怎么做呢?于是又去查看怎么根据http协议调用webservice并做了个无参接口测试,如下:(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误

但一做有参的接口调用就提示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错误也解决了。

测试代码如下:

   protected void Page_Load(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(System.Drawing.Image.FromFile("C:/Users/TYTD/Desktop/测试样本/ch_DJI_279.jpg"));
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Flush();
//将二进制数据存到byte数组中
byte[] bmpBytes1 = ms.ToArray();
bmp.Dispose(); string bmpBytes = HttpUtility.UrlEncode("bmpBytes") + "=" + HttpServerUtility.UrlTokenEncode(bmpBytes1); string url = "http://192.168.0.28:9800/WebService1.asmx/Send_Image";
string a = CallServiceByGet1(url, bmpBytes); }
public static string CallServiceByGet1(string strURL,string a)
{
var result = string.Empty;
//创建一个HTTP请求
byte[] byt = Encoding.UTF8.GetBytes(a);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byt.Length; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(byt, , byt.Length);
outputStream.Close(); HttpWebResponse response;
Stream responseStream;
StreamReader reader;
string srcString;
try
{
response = (HttpWebResponse)request.GetResponse();//获取http请求的响应对象
}
catch (WebException ex)
{
return ex.Message;
}
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
srcString = reader.ReadToEnd();
result = srcString; //返回值赋值
reader.Close(); return result;
}
上一篇:20170326 ABAP调用外部webservice实例


下一篇:c#中多线程同步Lock(锁)的研究以及跨线程UI的操作