Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send parameters on an Https POST with C#

I have asked here how to make the https post, and now that works fine. Problem now is How to send a parameter, name query, which is a JSON string:

{"key1":"value1", "key2":{"key21":"val21"} }

What I'm doing and doesn't work is:

HttpWebRequest q = (HttpWebRequest)WebRequest.Create(Host + ":" + Port);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
q.Method = "POST";
q.ContentType = "application/json";
q.Headers.Add("JSON-Signature", GetFirma(query));
q.Credentials = new NetworkCredential(user,pass);

byte[] buffer = Encoding.UTF8.GetBytes("query=" + query);

q.ContentLength = buffer.Length;

using (Stream stream = q.GetRequestStream())
{
     stream.Write(buffer, 0, buffer.Length);                    
}

But the server always answer saying there's no 'query' parameter. Any help?

like image 330
MaLKaV_eS Avatar asked Oct 08 '09 11:10

MaLKaV_eS


People also ask

Can we send parameters in POST request?

In a POST request, the parameters are sent as a body of the request, after the headers. To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

Can HTTP POST have query parameters?

POST should not have query param. You can implement the service to honor the query param, but this is against REST spec.

How do I send a parameter in a request?

Request parameters are used to send additional information to the server. A URL contains these parameters. There are two types of parameters: Query Parameter: These are appended to the end of the request URL, Query parameters are appended to the end of the request URL, following '?'

How do I send a https POST request?

Under HTTP request settings: Enter a URL in the field provided. Select either Use HTTP GET or Use HTTP POST. Enter HTTPS instead of HTTP in the URL to send the information using HTTPS.


1 Answers

I would use WebClient.UploadValues:

        using (WebClient client = new WebClient())
        {
            NameValueCollection fields = new NameValueCollection();
            fields.Add("query", query);
            byte[] respBytes = client.UploadValues(url, fields);
            string resp = client.Encoding.GetString(respBytes);
        }
like image 101
Marc Gravell Avatar answered Sep 24 '22 14:09

Marc Gravell