How to add parameters into a WebRequest?

205,425

Solution 1

If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.

If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:

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

Solution 2

Use stream to write content to 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();  

Solution 3

For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.

Solution 4

Hope this works

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

Solution 5

I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.

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();
Share:
205,425

Related videos on Youtube

Quan Mai
Author by

Quan Mai

Curious, flexible, reliable and committed, I define myself as one software developer who always want to face the most challenging problems. Successful or not, I always learn something and grow up, therefore contribute to my team, my company, and myself.

Updated on December 21, 2020

Comments

  • Quan Mai
    Quan Mai over 3 years

    I need to call a method from a webservice, so I've written this code:

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

    But this method requires some parameters, as following:

    Post data:

    _username:'API USER',         // api authentication username
    
    _password:'API PASSWORD',     // api authentication password
    

    How can I add these parameters into this Webrequest?

    Thanks in advance.

  • Smith
    Smith over 12 years
    what are the extra parameters you added to this newStream.Write(data,0,data.Length)
  • CoderHawk
    CoderHawk over 12 years
    @Smith - username and password, see the first line
  • RyanfaeScotland
    RyanfaeScotland over 9 years
    @Omid a number indicating how long the system should wait before giving up.
  • keeehlan
    keeehlan almost 9 years
    Seems convoluted compared to @CoderHawk's answer.
  • Jean-philippe Emond
    Jean-philippe Emond almost 8 years
    old topic but.. what is "Constant" ?
  • Susarla Nikhilesh
    Susarla Nikhilesh over 5 years
    Can I have an example ?
  • Nick
    Nick over 5 years
    Code-only answers are discouraged. Please click on edit and add some words summarising how your code addresses the question, or perhaps explain how your answer differs from the previous answer/answers. Thanks
  • MindRoasterMir
    MindRoasterMir over 2 years
    request.ContentLength --- request is not defined. thanks