为什么POST使用Webrequest总是失败,但是使用html形式却成功?

时间:2018-09-28 07:52:41

标签: c# system.net.httpwebrequest

我花了两天时间进行调试,但是找不到错误原因。 使用WebRequest调用servlet的应用程序客户端失败,WebException为“操作已超时”,但是当我通过html形式的POST方法调用servlet时成功。这是代码C#:

public string PostURLRequest(string URL, string postData)
{
    try
    {
        System.Text.Encoding enc =
            System.Text.Encoding.GetEncoding("shift_jis");

        byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);

        System.Net.HttpWebRequest req =
            (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
        req.ProtocolVersion = System.Net.HttpVersion.Version10;
        req.Method = "POST";
        req.ReadWriteTimeout = -1;
        req.KeepAlive = false;
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = postDataBytes.Length;
        req.Timeout = 10*60*1000;

        System.IO.Stream reqStream = req.GetRequestStream();

        reqStream.Write(postDataBytes, 0, postDataBytes.Length);
        reqStream.Close();

        System.Net.WebResponse res = req.GetResponse();//----------> THROW EXCEPTION HERE
        System.IO.Stream resStream = res.GetResponseStream();

        System.IO.StreamReader sr = new System.IO.StreamReader(resStream, enc);
        String text = sr.ReadToEnd();

        sr.Close();
        return text;
    }
    catch(System.Net.WebException ex)
    {
        if (ex.Status == System.Net.WebExceptionStatus.Timeout)
        {
            Console.WriteLine("Error: {0}", ex.Message);
        }
        return "NG";
    }
}

0 个答案:

没有答案