HttpWebResponse远程服务器返回错误: (500) 内部服务器错误 的解决办法

例子:

 

myHttpWebRequest.Method = "POST";
Console.WriteLine ("/nPlease enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri :");

// Create a new string object to POST data to the Url.
string inputData = Console.ReadLine ();


string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);
Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}", myHttpWebRequest.ContentLength);

// Close the Stream object.
newStream.Close ();

 

一般都是执行到 Stream newStream = myHttpWebRequest.GetRequestStream (); 的时候会抛出500 服务器错误,而且有时候会,有时候不会,本人试了很久才找到解决办法,

 

  原来是 myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; 这个的原因,改成

myHttpWebRequest.ContentType = "text/html"; 问题就解决了!汗!

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用C#中的WebClient类或HttpWebRequest类来实现上传文件至远程服务器。以下是一个使用WebClient类的示例: ```csharp using System.Net; string filePath = "C:/example.txt"; string uploadUrl = "http://example.com/upload"; WebClient client = new WebClient(); client.UploadFile(uploadUrl, filePath); ``` 在上面的示例中,你需要将`filePath`变量设置为你要上传的文件的本地路径,将`uploadUrl`变量设置为你要上传到的远程服务器的URL。然后,使用`UploadFile`方法将文件上传到远程服务器。 你还可以使用HttpWebRequest类来实现上传文件,这需要更多的代码来设置一个HTTP POST请求并将文件内容写入请求流中。以下是一个使用HttpWebRequest类的示例: ```csharp using System.IO; using System.Net; string filePath = "C:/example.txt"; string uploadUrl = "http://example.com/upload"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl); request.Method = "POST"; request.ContentType = "application/octet-stream"; request.ContentLength = new FileInfo(filePath).Length; using (Stream requestStream = request.GetRequestStream()) { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) { requestStream.Write(buffer, 0, bytesRead); } } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); ``` 在上面的示例中,你需要将`filePath`变量设置为你要上传的文件的本地路径,将`uploadUrl`变量设置为你要上传到的远程服务器的URL。然后,创建一个HttpWebRequest对象并设置请求的方法、内容类型和内容长度。接下来,打开本地文件并将其内容写入请求流中。最后,发送请求并获取响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值