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);
}
}
那麼,什麼是您的具體問題?如何將參數傳遞給'PostRequest'方法? –
標題是NameValueCollection或字典不是字符串數組 - 您不能用字符串數組表示鍵/值 – silverfighter