我正在尝试使用 iFrame 将 Moneris 托管支付页面集成到我的 .net 1.1 应用程序中。我以前做过很多次,但不是用 .net 1.1。我似乎找不到用 1.1 进行程序化 HTML 发布的好资源。有什么建议吗?
谢谢!
编辑:仔细研究给出的建议,我意识到 HttpWebRequest 解决方案不起作用,因为您不能与 POST 一起进行重定向。为了与 Moneris 正确集成,您必须发布金额值,然后重定向到您发布到的 URL。抱歉造成混淆。
最佳答案
您可以使用 HttpWebRequest和 HttpWebResponse类来实现这一目标。
例如,要 POST 到具有两个字段的 HTML 表单,username
和 password
,您可以这样做:
NameValueCollection nv = new NameValueCollection();
nv.Add("username", "bob");
nv.Add("password", "password");
string method = "POST"; // or GET
string url = "http://www.somesite.com/form.html";
HttpStatusCode httpStatusCode;
string response = SendHTTPRequest(nv, method, url, out httpStatusCode);
public static string SendHTTPRequest(NameValueCollection data,
string method,
string url,
out HttpStatusCode httpStatusCode)
{
StringBuilder postData = new StringBuilder();
foreach(string key in data)
{
postData.Append(key + "=" + data[key] + "&");
}
if(method == "GET" && data.Count > 0)
{
url += "?" + postData.ToString();
}
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = method;
httpWebRequest.Accept = "*/*";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
if(method == "POST")
{
using(Stream requestStream = httpWebRequest.GetRequestStream())
{
using(MemoryStream ms = new MemoryStream())
{
using(BinaryWriter bw = new BinaryWriter(ms))
{
bw.Write(Encoding.GetEncoding(1252).GetBytes(postData.ToString()));
ms.WriteTo(requestStream);
}
}
}
}
return GetWebResponse(httpWebRequest, out HttpStatusCode httpStatusCode);
}
private static string GetWebResponse(HttpWebRequest httpWebRequest,
out HttpStatusCode httpStatusCode)
{
using(HttpWebResponse httpWebResponse =
(HttpWebResponse)httpWebRequest.GetResponse())
{
httpStatusCode = httpWebResponse.StatusCode;
if(httpStatusCode == HttpStatusCode.OK)
{
using(Stream responseStream = httpWebResponse.GetResponseStream())
{
using(StreamReader responseReader = new StreamReader(responseStream))
{
StringBuilder response = new StringBuilder();
char[] read = new Char[256];
int count = responseReader.Read(read, 0, 256);
while(count > 0)
{
response.Append(read, 0, count);
count = responseReader.Read(read, 0, 256);
}
responseReader.Close();
return response.ToString();
}
}
}
return null;
}
}
关于c# - 使用 C#.NET 1.1 的程序化 HTML POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1731248/