以下是带有(更改的实际 URL 和凭据)的示例代码
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; });
var requestUri = new Uri("https://example.com/path1/path2?var=somevar");
byte[] data = Encoding.UTF8.GetBytes("DEV72*12/27/06*TAYLOR*RICH*JOE*10/28/56*U0999495102*466666666*01*TAYLOR*TAMMY*M*10/26/52***CIGNA HMO*62308*UPIN*MEDICAL CENTER**MESSAGE*M*F*30");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.PreAuthenticate = true;
request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential("UUUSSSEEERR", "PASSWORD");
request.ContentLength = data.Length;
request.ContentType = "text/plain";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
StreamReader streamReader = null;
string result;
try
{
streamReader = new StreamReader(request.GetResponse().GetResponseStream());
result = streamReader.ReadToEnd();
}
finally
{
streamReader.Close();
}
txtOutput.Text = result;
它总是在第一次运行时抛出错误的请求异常,但是当我将调试器中的光标移回第一行时,它可以正常工作并在 txtOutput.text 中给出正确的响应,并且在分离的应用程序中给出相同的行为,第一次它抛出异常但第二次它可以工作好的,有人可以给我一些工作或让我知道我在这里做错了什么。使用.net 4.0。
更新:
例如,下面的代码对我有用,但这不是我正在寻找的解决方法
var requestUri = new Uri("https://example.com/path1/path2?var=somevar");
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; });
byte[] data = Encoding.UTF8.GetBytes("DEV72*12/27/06*TAYLOR*RICH*JOE*10/28/56*U0999495102*466666666*01*TAYLOR*TAMMY*M*10/26/52***CIGNA HMO*62308*UPIN*MEDICAL CENTER**MESSAGE*M*F*30");
HttpWebRequest request = null;
int counter = 0;
do
{
request = (HttpWebRequest)WebRequest.Create(requestUri);
request.PreAuthenticate = true;
request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential("USERNAME", "password");
request.ContentLength = data.Length;
request.ContentType = "text/plain";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
StreamReader streamReader = null;
string result = string.Empty;
try
{
streamReader = new StreamReader(request.GetResponse().GetResponseStream());
result = streamReader.ReadToEnd();
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if (response.StatusCode == HttpStatusCode.BadRequest)
{
counter++;
}
else
{
txtOutput.Text = ex.ToString();
}
}
finally
{
if(streamReader != null) streamReader.Close();
}
txtOutput.Text = result;
} while (counter == 1);