如何发出 PUT HttpWebRequest

发布于 2025-01-01 04:55:58 字数 1307 浏览 0 评论 0原文

我正在尝试与需要 PUT 来更新数据的 API 集成:

这是他们使用curl 的示例:

curl --request PUT \
     --user-agent "您的客户端名称/1.0" \
     --header“内容类型:application/xml”\
     --data-binary '10' \
     https://www.example.com/api/v2/orders/101

但是,我需要使用 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞎闹 2025-01-08 04:55:58

好吧,这是一个可能的起源点——未经测试;直接写入浏览器;不是生产代码;假设 PUT 调用发送和接收相同的对象类型(可能不是这种情况)...

主要的补充是您需要提供请求的 ContentLength,并且需要将序列化的 JSON 对象写入请求流,您可以通过调用 HttpWebRequest::GetRequestStream() 来获取它。这与 POST 时的方法相同。

private T Call<T>(string url, string methodType, T data) where T: class
{
    T result;

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.Method = methodType;
    request.ContentType = "application/json";
    request.Accept = "application/json";

    if (methodType == "PUT" || methodType == "POST")
    {
       JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
       string jsonData = jsSerializer.Serialize(data);

       byte[] arrData = Encoding.UTF8.GetBytes(jsonData);
       request.ContentLength = arrData.Length;

       using (Stream dataStream = request.GetRequestStream())
       {
          dataStream.Write(arrData, 0, arrData.Length);
       }
    }

    // Note: You may not need to parse any response content,
    // or it may be a different class
    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;
}

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.

private T Call<T>(string url, string methodType, T data) where T: class
{
    T result;

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.Method = methodType;
    request.ContentType = "application/json";
    request.Accept = "application/json";

    if (methodType == "PUT" || methodType == "POST")
    {
       JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
       string jsonData = jsSerializer.Serialize(data);

       byte[] arrData = Encoding.UTF8.GetBytes(jsonData);
       request.ContentLength = arrData.Length;

       using (Stream dataStream = request.GetRequestStream())
       {
          dataStream.Write(arrData, 0, arrData.Length);
       }
    }

    // Note: You may not need to parse any response content,
    // or it may be a different class
    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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文