How to send multiple parameters to a Web API call using WebClient - c#

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)

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.

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.

Related

How to use sended post data on server side

I have a simple script to upload a file. Actually everything is working fine.
private void UploadCSV()
{
Uri address = new Uri("https://www.mydomain.xy/inc.upload.php");
string fileName = #"C:\test.csv";
using (WebClient client = new WebClient())
{
var parameters = new NameValueCollection();
parameters.Add("test", "aaaa");
client.QueryString = parameters;
client.UploadProgressChanged += WebClientUploadProgressChanged;
client.UploadFileCompleted += WebClientUploadCompleted;
client.UploadFileAsync(address, "POST", fileName);
}
}
Now as you can see, I try so send some data via POST test what contains aaaa. But now matter how I try to select the data serverside... there is nothing....
I tried $_POST['test'], $_POST['data']['test'].... but no results.
How can I access the extra Data ?
client.QueryString = parameters;
This will append a query string to the URL that you send the data to.
Even though the request method is POST, PHP always provides the query string parameters in $_GET.

Get raw querystring of WebClient in C#

I'm using a WebClient to make a POST request with a query string but I can't see the raw string. This is what I have:
WebClient TheWebClient = new WebClient();
TheWebClient.QueryString.Add("Param1", "1234");
TheWebClient.QueryString.Add("Param2", "4567");
TheWebClient.QueryString.Add("Param3", "4539");
var TheResponse = TheWebClient.UploadValues("https://www.example.com/posturl", "POST", TheWebClient.QueryString);
string TheResponseString = TheWebClient.Encoding.GetString(TheResponse);
//problem is that this only shows the keys
var RawQueryString = TheWebClient.QueryString;
How can I see the actual raw query string?
WebClient.UploadValues doesn't save the request "raw query string" simply because you provided it with them, and it's not gonna change, thus is redundant.
Furthermore, HttpPost requests doesn't use query string for the request payload, it has a url, a message payload; which is appended after the headers, maybe query string. Thus there is nothing new the client class should let you know, so it won't save it.

Accessing query string variables sent as POST in HttpActionContext

I'm trying to access a query string parameter that was sent using the POST method (WebClient) to the Web API in ASP.NET MVC 5 (in an overridden AuthorizationFilterAttribute).
For Get, I've used the following trick:
var param= actionContext.Request.GetQueryNameValuePairs().SingleOrDefault(x => x.Key.Equals("param")).Value;
However, once I use POST, this does work and the variable paran is set to null. I think that's because the query string method only applies to the url, not the body. Is there any way to get the query string (using one method preferably) for both GET and POST requests?
EDIT: WebClient Code
using (WebClient client = new WebClient())
{
NameValueCollection reqparm = new NameValueCollection();
reqparm.Add("param", param);
byte[] responsebytes = client.UploadValues("https://localhost:44300/api/method/", "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responsebody);
}
}
Using the code you show, you upload the param=value in the request body using the application/x-www-form-urlencoded content-type.
If you also want to utilize the query string, you need to set it separately using the WebClient.QueryString property:
// Query string parameters
NameValueCollection queryStringParameters = new NameValueCollection();
queryStringParameters.Add("someOtherParam", "foo");
client.QueryString = queryStringParameters;
// Request body parameters
NameValueCollection requestParameters = new NameValueCollection();
requestParameters.Add("param", param);
client.UploadValues(uri, method, requestParameters);
This will make the request go to uri?someOtherParam=foo, enabling you to read the query string parameters serverside through actionContext.Request.GetQueryNameValuePairs().

unable to send json data in c#

I am sending my JSON string to this url http://myipaddress/WindowsApp/Registration?data=
I am using the following code which is as follows :
internal static async Task<String> getHttpResponse(HttpWebRequest request,string postData)
{
String received = null;
byte[] requestBody = Encoding.UTF8.GetBytes(postData);
using(var postStream=await request.GetRequestStreamAsync())
{
await postStream.WriteAsync(requestBody, 0, requestBody.Length);
}
try
{
var response = (HttpWebResponse)await request.GetResponseAsync();
if(response != null)
{
var reader = new StreamReader(response.GetResponseStream());
received = await reader.ReadToEndAsync();
}
}
catch(WebException ae)
{
var reader = new StreamReader(ae.Response.GetResponseStream());
string responseString = reader.ToString();
Debug.WriteLine("################ EXCEPTIONAL RESPONSE STRING ################");
Debug.WriteLine(responseString);
return responseString;
}
return received;
}
and I am calling this method when I click on one of my buttons in XAML as follows :
HttpWebRequest request = HttpWebRequest.Create(Classes.Constants.SERVER_URL) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
postData = JsonConvert.SerializeObject(user);
string receivedString = await getHttpResponse(request, postData);
Debug.WriteLine("############# RECEIVED STRING #############");
Debug.WriteLine(receivedString);
So, the problem I am facing is that I am unable to get the string on the server.
Note : I am able to get the json string when my server implements its method with a url : http://myipaddress/WindowsApp/Registration
(without parameter "?data=") and also sends me response string. But fails when the term "?data=" is implemented and used in the server url.
So what am I going wrong in my code? Please help.
So, from what I see in the code you posted, from client side perspective(since we don't see the server side code)you are sending a request to the server in the body of the request.
There are two ways to POST: one way in the body of the request, the other one in the query string.
Seems to me that you are mixing the two.
When you do a POST request to your server to the address without the ?data=
then you send the request in the body.
Solutions:
If you want to POST in the body of the request, POST to the address without the ?data= parameter in the query string
If you want to send it trough the query string, you need to add the value after the ?data=
something like:
http://myipaddress/WindowsApp/Registration?data=MyValue
If I have understood everything correctly, you are trying to send a POST request to the server and to get a response from the server?
The POST request methods documentation says, that POST request must be used to submit data, not to get a response.
Note that query strings (name/value pairs) is sent in the HTTP message body of a POST request like this:
POST /test/demo_form.asp HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
Your Url should be http://myipaddress/WindowsApp/Registration since you are posting your data in the payload.

HTTP POST with JSON object returned c#

I am trying to create a HTTP Post that returns a JSON object with 2 attributes.
Details are below:
HTTP POST to http://text-processing.com/api/sentiment/ with form encoded data which contains a string. A JSON object response with 2 attributes is retuned; lable and negative.
I am tying to do this in c#, which is where I am struggling.
Thank you
You can try using a WebClient like this
WebClient webclient = new WebClient();
NameValueCollection postValues = new NameValueCollection();
postValues.Add("foo", "fooValue");
postValues.Add("bar", "barValue");
byte[] responseArray = webclient.UploadValues(*url*, postValues);
string returnValue = Encoding.ASCII.GetString(responseArray);
MSDN page also has an example.

Categories

Resources