Search code examples
http-posthttpwebrequestquery-stringhttpwebresponseurl-parameters

Server returns "Unable to connect to the remote server" when querystring parameters sent in body as byte


I have below code to make a POST and retrieve the response:

string url = // Url. Example= "https://www.mywebsite.com"
string body = // querystring values I would like to pass as parameter. Example= "Param1=Value1&Param2=Value2&Param3=Value3"

byte[] byteBody = Encoding.GetEncoding("iso-8859-1").GetBytes(body);
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = false;
httpWebRequest.ContentLength = byteBody.Length;

Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(byteBody, 0, byteBody.Length);
requestStream.Flush();
(HttpWebResponse)httpWebRequest.GetResponse();

When I set url and body parameters as below, this code works for so many URLs without a problem.

string url = "https://www.mywebsite.com";
string body = "Param1=Value1&Param2=Value2&Param3=Value3";

But there is one URL which does not. When I set parameters like above, it returns "Unable to connect to the remote server".

But, when I set the parameters like below, it works:

string url = "https://www.mywebsite.com?Param1=Value1&Param2=Value2&Param3=Value3";
string body = "";

What would be the reason? What is the difference between sending the parameters in Querystring of URL and write to the stream? And is the first approach move secure or more solid, or there is absolutely no difference between them?


Solution

  • Well, it depends on what server-side is expecting for this api. The fact that the api is responding correctly to the call

    string url = "https://www.mywebsite.com?Param1=Value1&Param2=Value2&Param3=Value3";
    string body = "";
    

    indicates that probably is expecting a GET call not a POST.