我的网站上有一个表单。用户输入他们的电子邮件并从下拉列表中选择一个位置。然后,我需要通过在查询字符串中点击用户位置和电子邮件的URL来将该数据发布到外部站点。
我这样做是这样的:
string url = "http://www.site.com/page.aspx?location=" + location.Text + "&email=" + email.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
我的客户说我没有打他们的服务器,但是在通过调试器时,我从他们的服务器得到了响应。我还尝试使用Firebug跟踪发生的事情,我注意到没有对该外部站点进行过POST。
我在这里做错了什么?
答案 0 :(得分:5)
string line;
HttpWebRequest request = WebRequest.Create("http://www.yahoo.com") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader streamr = new StreamReader(response.GetResponseStream());
line = streamr.ReadToEnd();
你可以找到我已经写完
的帖子答案 1 :(得分:3)
确保您正在执行POST而不是GET方法。这是我过去使用的一些类似代码。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.Timeout = 30000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
答案 2 :(得分:2)
检查您WebRequest
使用的Method
。我假设它默认为GET
,而不是POST
。
您可以自己轻松设置:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
答案 3 :(得分:1)
从我在这里看到的代码,我不得不说你的客户端是错的,你正在打他们的服务器(假设site.com是他们的服务器,你有一个有效的互联网连接:)。但是,如果您需要执行POST而不是GET来发送数据,可能类似于以下内容:
string url = "http://www.site.com/page.aspx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// set request properties
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// set post values
string postValues = "location=" + location.Text + "&email=" + email.Text;
request.ContentLength = postValues.Length;
// write post values
StreamWriter streamWriter = new StreamWriter (request.GetRequestStream(), System.Text.Encoding.ASCII);
streamWriter.Write(postValues);
streamWriter.Close();
// process response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseData = streamReader.ReadToEnd();
streamReader.Close();
// do any processing needed on responseData...