問題
下記のHttpWebRequestは必要なheaderを設定しましたが、どうしても500エラーを返してきます。
APIのテストは、postmanで試してみました、headerとbodyの設定は問題ないです。
何時間を調査すると、https://www.orcode.com/question/943479_k955ab.htmlで解決方法を見つけました。
解決方法
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;)");を追加することで、問題を解決しました!
問題あるソース
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