0

I want to send via POST request two parameters to a Web API service. I am currently receiving 404 not found when I try in the following way, as from msdn:

public static void PostString (string address)
{
    string data = "param1 = 5 param2 = " + json;
    string method = "POST";
    WebClient client = new WebClient ();
    string reply = client.UploadString (address, method, data);

    Console.WriteLine (reply);
}

where json is a json representation of an object. This did not worked, I have tried with query parameters as in this post but the same 404 not found was returned.

Can somebody provide me an example of WebClient which sends two parameters to a POST request?

Note: I am trying to avoid wrapping both parameters in the same class only to send to the service (as I found the suggestion here)

Community
  • 1
  • 1
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76

2 Answers2

0

I would suggest sending your parameters as a NameValueCollection.

Your code would look something like this when sending the parameters with a NameValueCollection:

using(WebClient client = new WebClient())
        {
            NameValueCollection requestParameters = new NameValueCollection();
            requestParameters.Add("param1", "5");
            requestParameters.Add("param2", json);
            byte[] response = client.UploadValues("your url here", requestParameters);
            string responseBody = Encoding.UTF8.GetString(response);
        }

Using UploadValues will make it easier for you, since the framework will construct the body of the request and you won't have to worry about concatenating parameters or escaping characters.

Kerim Emurla
  • 1,141
  • 8
  • 15
0

I have managed to send both a json object and a simple value parameter by sending the simple parameter in the address link and the json as body data:

public static void PostString (string address)
{
    string method = "POST";
    WebClient client = new WebClient ();
    string reply = client.UploadString (address + param1, method, json);

    Console.WriteLine (reply);
}

Where address needs to expect the value parameter.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76