从Postman工作正常的Windows窗体进行API调用超时

时间:2017-06-28 10:06:24

标签: c# winforms api timeout postman

我正试图从Windows窗体中调用API进入超时状态。但它在POSTMAN应用程序中工作正常。

我正在使用以下代码从Windows应用程序调用Web API。

public string ReadXMLResponse(string strrequestxml, string strTallyServer1)
{
    string URL = strTallyServer1;

    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
    myHttpWebRequest.Accept = "application/xml";
    myHttpWebRequest.ContentType = "application/xml";
    myHttpWebRequest.Timeout = 60000;

    string method = "POST";
    myHttpWebRequest.Method = method;
    if (method == "POST")
    {
        using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(strrequestxml);
            streamWriter.Flush();
        }
    }

    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

    using (var streamReader = new StreamReader(myHttpWebResponse.GetResponseStream()))
    {
        var streamRead = streamReader.ReadToEnd().Trim();
        return streamRead;
    }
    return "";
}

1 个答案:

答案 0 :(得分:0)

我有相同的代码和相同的问题。直到我在微软的一个博客上发现了一些东西,这让我很生气。试图谷歌原来的页面,但我找不到它。

WebRequest request = WebRequest.Create("URL");
request.Method = "POST";
var postData = string.Format(dataFormnat, Uri.EscapeDataString(data.Serialize()));

byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

reader.Close();
dataStream.Close();
response.Close();