2011-02-28 57 views
40

在C#中組成靜態PUT請求的最佳方式是什麼?如何進行HTTP PUT請求?

該請求還必須發送URI中不存在的對象。

+3

PUT是HTTP。 REST是一種架構,而不是協議。 – 2011-02-28 10:26:42

+0

是的,但在這個特定的問題,我在特定的情況下使用HTTP,即休息... – Marcom 2011-02-28 12:36:10

回答

45
using(var client = new System.Net.WebClient()) { 
    client.UploadData(address,"PUT",data); 
} 
+0

我用了一個稍微不同的方法,但這很好。謝謝 – Marcom 2011-02-28 17:10:24

+2

介紹如何向此添加oauth標頭? – 2015-12-29 05:28:20

+3

@toing_toing你通過'client.Headers.Add(...);'添加頭文件。至於名字/價值應該是什麼 - 你必須自己研究 – 2015-12-29 10:24:02

27

我最後的處理方法:

public void PutObject(string postUrl, object payload) 
     { 
      var request = (HttpWebRequest)WebRequest.Create(postUrl); 
      request.Method = "PUT"; 
      request.ContentType = "application/xml"; 
      if (payload !=null) 
      { 
       request.ContentLength = Size(payload); 
       Stream dataStream = request.GetRequestStream(); 
       Serialize(dataStream,payload); 
       dataStream.Close(); 
      } 

      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      string returnString = response.StatusCode.ToString(); 
     } 

public void Serialize(Stream output, object input) 
      { 
       var ser = new DataContractSerializer(input.GetType()); 
       ser.WriteObject(output, input); 
      } 
1

protected void UpdateButton_Click(object sender, EventArgs e) 
     { 
      var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text); 
      var bytes = Encoding.ASCII.GetBytes(values); 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees")); 
      request.Method = "PUT"; 
      request.ContentType = "application/x-www-form-urlencoded"; 
      using (var requestStream = request.GetRequestStream()) 
      { 
       requestStream.Write(bytes, 0, bytes.Length); 
      } 
      var response = (HttpWebResponse) request.GetResponse(); 

      if (response.StatusCode == HttpStatusCode.OK) 
       UpdateResponseLabel.Text = "Update completed"; 
      else 
       UpdateResponseLabel.Text = "Error in update"; 
     } 
0

如何使用WebRequest的使用PUT方法。

//JsonResultModel class 
    public class JsonResultModel 
    { 
     public string ErrorMessage { get; set; } 
     public bool IsSuccess { get; set; } 
     public string Results { get; set; } 
    } 
    // HTTP_PUT Function 
    public static JsonResultModel HTTP_PUT(string Url, string Data) 
    { 
     JsonResultModel model = new JsonResultModel(); 
     string Out = String.Empty; 
     string Error = String.Empty; 
     System.Net.WebRequest req = System.Net.WebRequest.Create(Url); 

     try 
     { 
      req.Method = "PUT"; 
      req.Timeout = 100000; 
      req.ContentType = "application/json"; 
      byte[] sentData = Encoding.UTF8.GetBytes(Data); 
      req.ContentLength = sentData.Length; 

      using (System.IO.Stream sendStream = req.GetRequestStream()) 
      { 
       sendStream.Write(sentData, 0, sentData.Length); 
       sendStream.Close(); 

      } 

      System.Net.WebResponse res = req.GetResponse(); 
      System.IO.Stream ReceiveStream = res.GetResponseStream(); 
      using (System.IO.StreamReader sr = new 
      System.IO.StreamReader(ReceiveStream, Encoding.UTF8)) 
      { 

       Char[] read = new Char[256]; 
       int count = sr.Read(read, 0, 256); 

       while (count > 0) 
       { 
        String str = new String(read, 0, count); 
        Out += str; 
        count = sr.Read(read, 0, 256); 
       } 
      } 
     } 
     catch (ArgumentException ex) 
     { 
      Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message); 
     } 
     catch (WebException ex) 
     { 
      Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message); 
     } 
     catch (Exception ex) 
     { 
      Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message); 
     } 

     model.Results = Out; 
     model.ErrorMessage = Error; 
     if (!string.IsNullOrWhiteSpace(Out)) 
     { 
      model.IsSuccess = true; 
     } 
     return model; 
    }