2012-10-16 73 views
1

我很努力地將POST方法用於RESTful服務。我的要求是我需要追加一些參數(不在URL中)和2個參數,我需要從文件中讀取。該服務是用Java編寫的。在.net中向POST方法發送多個參數:

string url= "http://srfmdpimd2:18109/1010-SF-TNTIN/Configurator/rest/importConfiguration/" 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
FileStream file = new FileStream(@"TestSCDS.properties", FileMode.Open); 
Byte[] bytes = new Byte[file.Length]; 
file.Read(bytes, 0, bytes.Length); 
string strresponse = Encoding.UTF8.GetString(bytes); 

request.Method = "POST"; 
request.ContentType = "multipart/form-data;"; 
request.ContentLength = file.Length; 

request.Headers.Add("hhrr", "H010"); 
request.Headers.Add("env", "TEST"); 
request.Headers.Add("buildLabel", "TNTAL_05.05.0500_C54"); 

Stream Postdata = request.GetRequestStream(); 
Postdata.Write(bytes, 0, bytes.Length); 
HttpWebResponse response = (HttpWebResponse)request.GetResponse();` 

request.Headers.Add()是將參數添加到URL?如果沒有,我怎樣才能發送多個參數POST方法在寧靜的服務?

另外,如何從文件中讀取參數並在POST方法中使用?

回答

0

我不知道你的完整要求是什麼,但我強烈的建議是「開始簡單」。

不是除非您確定需要它,否則請使用「Content-type:multipart/form-data」。相反,從「application/x-www-form-urlencoded」(舊的最愛)或「application/json」(甚至更好)開始。

這是一個很好的一步一步的例子。你可以從字面上100的多用一個簡單的谷歌搜索發現:

1

它需要一些跑腿的活兒,編碼字典,並把它在體內。以下是一個快速示例:

private string Send(string url) 
{ 
     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 

     request.Method = "POST"; 

     string postData = EncodeDictionary(args, false); 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] postDataBytes = encoding.GetBytes(postData); 

     request.ContentType = "application/x-www-form-urlencoded"; 
     request.ContentLength = postDataBytes.Length; 

     using(Stream requestStream = request.GetRequestStream()) 
     { 
      requestStream.Write(postDataBytes, 0, postDataBytes.Length); 
     } 

     using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
     { 
      StreamReader reader = new StreamReader(response.GetResponseStream()); 
      return reader.ReadToEnd(); 
     } 
} 

private string EncodeDictionary(Dictionary<string, string> dict, 
           bool questionMark) 
{ 
    StringBuilder sb = new StringBuilder(); 
    if (questionMark) 
    { 
     sb.Append("?"); 
    } 
    foreach (KeyValuePair<string, string> kvp in dict) 
    { 
     sb.Append(HttpUtility.UrlEncode(kvp.Key)); 
     sb.Append("="); 
     sb.Append(HttpUtility.UrlEncode(kvp.Value)); 
     sb.Append("&"); 
    } 
    sb.Remove(sb.Length - 1, 1); // Remove trailing & 
    return sb.ToString(); 
}