Search code examples
c#restc#-4.0httpwebrequesthttp-get

HttpGet with parameters using HttpWebResponse C#


I'm trying to perform a GET with added parameters. I was previously using WebClient code which suddenly stopped working so I've decided to switch to using HttpWebRequest/HttpWebResponse. How do you go about adding parameters properly? I have a REST function that takes in two string parameters, but I can't get it to see them. Basically, how do I add multiple parameters to a GET call?

Here's my GET code (booksString is a comma-separated string of book ids):

string webAddress = "http://localhost:5000/stuff/address";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddress);
request.Headers.Add("bookIds", booksString);
request.Method = "GET";
request.Accept = "text/html";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
string text = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (StreamReader reader = new StreamReader(response.GetResponseStream(),
             Encoding.ASCII))
    {
        text = reader.ReadToEnd();
    }
}
Console.WriteLine("text: " + text);

and here is my REST code:

public List<Book> GetBooks(string bookIds, string param2)
{
    Console.WriteLine("book IDs: " + bookIds + " " + param2);
}

Whenever I run this code bookIds is empty? How do I send multiple parameters and have my REST function recognize the data?


Solution

  • Try using URL encoding.

    http://localhost:5000/stuff/address?bookIds={0}&param2={1}

    Use string.format to fill the values and make the call.