将标头传递给webRequest作为参数

时间:2015-12-14 13:55:09

标签: c#

如果我们有通用的httpWebRequest方法,并且如果我们通过参数传递头文件,我们如何将它们作为字符串传递?

方法示例和标题作为参数。我们如何将标题传递给方法?

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);
            }
        }

1 个答案:

答案 0 :(得分: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();