2015-12-14 28 views
0

如果我們有通用的httpWebRequest方法,並且如果我們通過參數傳遞標頭,我們如何將它們作爲字符串傳遞?將標題傳遞給webRequest作爲參數

作爲參數的方法和標題的示例。我們如何將標題傳遞給方法?

public static HttpWebResponse PostRequest(string url, string usrname, string pwd, string method, string contentType, 
             string[] headers, string body) 
     { 
      // Variables. 
      HttpWebRequest Request; 
      HttpWebResponse Response; 
      // 
      string strSrcURI = url.Trim(); 
      string strBody = body.Trim(); 

      try 
      { 
       // Create the HttpWebRequest object. 
       Request = (HttpWebRequest)HttpWebRequest.Create(strSrcURI); 

       if (string.IsNullOrEmpty(usrname) == false && string.IsNullOrEmpty(pwd) == false) 
       { 
        // Add the network credentials to the request. 
        Request.Credentials = new NetworkCredential(usrname.Trim(), pwd); 
       } 

       // Specify the method. 
       Request.Method = method.Trim(); 

       // request headers 
       foreach (string s in headers) 
       { 
        Request.Headers.Add(s); 
       } 

       // Set the content type header. 
       Request.ContentType = contentType.Trim(); 

       // set the body of the request... 
       Request.ContentLength = body.Length; 
       using (Stream reqStream = Request.GetRequestStream()) 
       { 
        // Write the string to the destination as a text file. 
        reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length); 
        reqStream.Close(); 
       } 

       // Send the method request and get the response from the server. 
       Response = (HttpWebResponse)Request.GetResponse(); 

       // return the response to be handled by calling method... 
       return Response; 
      } 
      catch (Exception e) 
      { 
       throw new Exception("Web API error: " + e.Message, e); 
      } 
     } 
+0

那麼,什麼是您的具體問題?如何將參數傳遞給'PostRequest'方法? –

+1

標題是NameValueCollection或字典不是字符串數組 - 您不能用字符串數組表示鍵/值 – silverfighter

回答

0

您可以使用流寫入內容的WebRequest:

string data = "username=<value>&password=<value>"; //replace <value> 
byte[] dataStream = Encoding.UTF8.GetBytes(data); 
private string urlPath = "http://xxx.xxx.xxx/manager/"; 
string request = urlPath + "index.php/org/get_org_form"; 
WebRequest webRequest = WebRequest.Create(request); 
webRequest.Method = "POST"; 
webRequest.ContentType = "application/x-www-form-urlencoded"; 
webRequest.ContentLength = dataStream.Length; 
Stream newStream=webRequest.GetRequestStream(); 
// Send the data. 
newStream.Write(dataStream,0,dataStream.Length); 
newStream.Close(); 
WebResponse webResponse = webRequest.GetResponse();