如何发出 PUT HttpWebRequest
我正在尝试与需要 PUT 来更新数据的 API 集成:
这是他们使用curl 的示例:
curl --request PUT \ --user-agent "您的客户端名称/1.0" \ --header“内容类型:application/xml”\ --data-binary '
' \ https://www.example.com/api/v2/orders/101 10
但是,我需要使用 .NET MVC 3 使用 JSON(他们也支持)。知道如何做到这一点吗?
我使用下面的代码成功获取了:
Order obj = Call<Order>(url, "GET");
private T Call<T>(string url, string methodType) where T : class {
T result;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = methodType;
request.Accept = "application/json";
request.ContentType = "application/json";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
result = (T)jsSerializer.Deserialize<T>(jsonData);
}
return result;
}
但是,我可以使用类似的方法发出 PUT 吗?
Order obj = Call<Order>(url, "PUT");
如果是这样,我应该将“数据二进制”所需的数据放在哪里?
I'm trying to integrate with an API that requires a PUT to update data:
Here's an example from them using curl:
curl --request PUT \ --user-agent "Your Client Name/1.0" \ --header "Content-Type: application/xml" \ --data-binary '<order><status_id>10</status_id></order>' \ https://www.example.com/api/v2/orders/101
However, I'd need to use JSON (they support that as well) using .NET MVC 3. Any idea on how I can do that?
I use the code below for GET successfully:
Order obj = Call<Order>(url, "GET");
private T Call<T>(string url, string methodType) where T : class {
T result;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = methodType;
request.Accept = "application/json";
request.ContentType = "application/json";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
result = (T)jsSerializer.Deserialize<T>(jsonData);
}
return result;
}
However, can I issue a PUT using a similar method?
Order obj = Call<Order>(url, "PUT");
If so, where do I put the data that's required in "data-binary"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,这是一个可能的起源点——未经测试;直接写入浏览器;不是生产代码;假设 PUT 调用发送和接收相同的对象类型(可能不是这种情况)...
主要的补充是您需要提供请求的 ContentLength,并且需要将序列化的 JSON 对象写入请求流,您可以通过调用 HttpWebRequest::GetRequestStream() 来获取它。这与 POST 时的方法相同。
Well, here's a possible point of origin - untested; written straight into the browser; not production code; assumes that the PUT call both sends and receives the same object type (which is probably not the case)...
The main addition is that you need to supply the request's ContentLength, and you need to write the serialized JSON object to the request stream, which you'll get by calling HttpWebRequest::GetRequestStream(). It's the same approach as when POSTing.