如何将参数添加到WebRequest中?

时间:2010-07-19 09:37:03

标签: c# .net web-services httpwebrequest

我需要从webservice调用一个方法,所以我写了这段代码:

 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.
 webRequest.ContentLength = 0;
 WebResponse webResponse = webRequest.GetResponse();

但是这种方法需要一些参数,如下所示:

发布数据:

_username:'API USER',         // api authentication username

_password:'API PASSWORD',     // api authentication password

如何将这些参数添加到此Webrequest中?

提前致谢。

6 个答案:

答案 0 :(得分:73)

使用流将内容写入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();  

答案 1 :(得分:31)

如果这些是url-string的参数,那么你需要通过'?'添加它们和'&amp;'字符,例如http://example.com/index.aspx?username=Api_user&password=Api_password

如果这些是POST请求的参数,那么您需要创建POST数据并将其写入请求流。以下是示例方法:

private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
                                        CookieContainer cookieContainer,
                                        string userAgent, string acceptHeaderString,
                                        string referer,
                                        string contentType, out string responseUri)
        {
            var result = "";
            if (!string.IsNullOrEmpty(requestUri))
            {
                var request = WebRequest.Create(requestUri) as HttpWebRequest;
                if (request != null)
                {
                    request.KeepAlive = true;
                    var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                    request.CachePolicy = cachePolicy;
                    request.Expect = null;
                    if (!string.IsNullOrEmpty(method))
                        request.Method = method;
                    if (!string.IsNullOrEmpty(acceptHeaderString))
                        request.Accept = acceptHeaderString;
                    if (!string.IsNullOrEmpty(referer))
                        request.Referer = referer;
                    if (!string.IsNullOrEmpty(contentType))
                        request.ContentType = contentType;
                    if (!string.IsNullOrEmpty(userAgent))
                        request.UserAgent = userAgent;
                    if (cookieContainer != null)
                        request.CookieContainer = cookieContainer;

                    request.Timeout = Constants.RequestTimeOut;

                    if (request.Method == "POST")
                    {
                        if (postData != null)
                        {
                            request.ContentLength = postData.Length;
                            using (var dataStream = request.GetRequestStream())
                            {
                                dataStream.Write(postData, 0, postData.Length);
                            }
                        }
                    }

                    using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpWebResponse != null)
                        {
                            responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
                            cookieContainer.Add(httpWebResponse.Cookies);
                            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            {
                                result = streamReader.ReadToEnd();
                            }
                            return result;
                        }
                    }
                }
            }
            responseUri = null;
            return null;
        }

答案 2 :(得分:8)

答案 3 :(得分:4)

希望这有效

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

答案 4 :(得分:0)

下面的代码不同于所有其他代码,因为最后,它在请求返回的控制台中打印响应字符串。我在以前的帖子中了解到用户没有获得响应流并显示它。

//Visual Basic Implementation Request and Response String
  Dim params = "key1=value1&key2=value2"
    Dim byteArray = UTF8.GetBytes(params)
    Dim url = "https://okay.com"
    Dim client = WebRequest.Create(url)
    client.Method = "POST"
    client.ContentType = "application/x-www-form-urlencoded"
    client.ContentLength = byteArray.Length
    Dim stream = client.GetRequestStream()

    //sending the data
    stream.Write(byteArray, 0, byteArray.Length)
    stream.Close()

//getting the full response in a stream        
Dim response = client.GetResponse().GetResponseStream()

//reading the response 
Dim result = New StreamReader(response)

//Writes response string to Console
    Console.WriteLine(result.ReadToEnd())
    Console.ReadKey()

答案 5 :(得分:0)

我觉得您发送的用户名和密码应该是授权标头的一部分。因此,以下代码向您展示了如何创建用户名和密码的Base64字符串。我还提供了一个发送POST数据的示例。就我而言,这是一个phone_number参数。

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;

string data = "phone_number=19735559042"; 
byte[] dataStream = Encoding.UTF8.GetBytes(data);

request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();