0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# WebRequest WebException: The remote server returned an error: (500) Internal Server Error

Last updated at Posted at 2022-10-26

問題

下記のHttpWebRequestは必要なheaderを設定しましたが、どうしても500エラーを返してきます。
APIのテストは、postmanで試してみました、headerとbodyの設定は問題ないです。
何時間を調査すると、https://www.orcode.com/question/943479_k955ab.htmlで解決方法を見つけました。

解決方法

image.png
WebClientは、実際に、user-agentなど選択可能のheaderをデフォルトに設定してくれないです。
APIのリクエストはuser-agentなどのheaderが必要がある場合、設定しないと、サーバーは500エラーが帰ってきます。
今回は、httpRequest.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");を追加することで、問題を解決しました!
image.png

問題あるソース

           var url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";

            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Method = "POST";

            httpRequest.ContentType = "text/xml; charset=utf-8;";
            httpRequest.Headers["SOAPAction"] = "http://WebXml.com.cn/getWeatherbyCityName";

            var data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\"><theCityName>北京</theCityName></getWeatherbyCityName></soap:Body></soap:Envelope>";

            using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
            {
                streamWriter.Write(data);
            }

            
            var httpResponse = (HttpWebResponse)httpRequest.GetResponse();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();

                logger.Info(result);
            }

            Console.WriteLine(httpResponse.StatusCode);

参考サイト

https://www.orcode.com/question/943479_k955ab.html
https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?