做一个HTTP POST到一个REST端点
我试图做一个简单的HTTP发布带有只有url参数的端点。做一个HTTP POST到一个REST端点
至少,这是我如何理解以下说明:
POST到该地址有一个参数名为url,改变了饲料的地址。
与XML-RPC方法一样,它验证Feed是否已更改,如果是,则通知订阅者。
事件已记录。返回值是一个名为result的XML消息,具有两个属性success和msg。
这是目前我的代码:
public static void ping(string feed)
{
HttpWebResponse response = MakeRequest(feed);
XmlDocument document = new XmlDocument();
document.Load(response.GetResponseStream();
string success = document.GetElementById("success").InnerText;
string msg = document.GetElementById("msg").InnerText;
MessageBox.Show(msg, success);
}
private static HttpWebResponse MakeRequest(string postArgument)
{
string url = path + "?" + UrlEncode(postArgument);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
return (HttpWebResponse)request.GetResponse();
}
private static string UrlEncode(string value)
{
string result;
result= HttpUtility.UrlEncode("url") + "=" + HttpUtility.UrlEncode(value);
return result;
}
我从服务器获取不正确的响应,所以我认为我做错了莫名其妙。这里是响应:
在文档的顶层无效。错误处理资源“文件:/// C:/Users/ADMIN/AppData/Local/Temp/VSD1.tmp.XML ...
街 ^
任何想法?
在此先感谢
这里是我找到工作的代码。
我们使用HTTP POST,在流的主体中编码参数。这给了我们“url-foobar”作为内容主体。在内容中没有内容类型,性格,边界等。
private static HttpWebResponse MakeRequest(string path, string postArgument)
{
//string url = path + "?" + UrlEncode(postArgument);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
request.Method = "POST";
string boundary = Guid.NewGuid().ToString().Replace("-", "");
request.ContentType = "multipart/form-data; boundary=" + boundary;
Stream stream = request.GetRequestStream();
string result = string.Format("url={0}", postArgument);
byte[] value = Encoding.UTF8.GetBytes(result);
stream.Write(value, 0, value.Length);
stream.Close();
return (HttpWebResponse)request.GetResponse();
}
public static void ping(string server, string feed)
{
HttpWebResponse response = MakeRequest(server, feed);
XmlDocument document = new XmlDocument();
string result = GetString(response.GetResponseStream());
try
{
document.LoadXml(result);
}
catch
{
MessageBox.Show("There was an error with the response", "Error");
}
//MessageBox.Show(msg, success);
}
public static string GetString(Stream thestream)
{
int n = thestream.ReadByte();
byte[] bytes = new byte[n];
thestream.Read(bytes, 0, n);
return Encoding.ASCII.GetString(bytes);
}
对GetString的调用仅用于调试目的,并非严格需要。
感谢大家谁插在这里让我走上正轨。
我不知道.NET的API,但我明白的说明为:“执行与查询参数的URL后”,和后体应该有url = foobar参数。
IOW:不是采用postArgument并将其追加到url,而是应该调用url并在消息正文中提供正确编码的url = foobar。
此外:我没有看到您设置请求“Accept”标头,如果服务器使用它来识别响应的格式,这可能很重要。
在.NET中执行表单发布的最佳方式是使用WebClient类。该类将以POST(实体主体中的参数)或GET(参数编码为查询字符串参数)的方式发送数据。
而你需要向我们展示了实际的异常客户端的回馈,为了弄清楚什么是错的..
你从服务器得到什么回应? – 2009-10-27 23:40:46