简体   繁体   中英

HttpWebRequest returns (400) Bad Request

The request gives the following error: The remote server returned an error: (400) Bad Request.

I cann't find a solution on internet. Does anyone knows how to solve this?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://maps.googleapis.com/maps/api/geocode/json");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            var parameters = string.Format("language={0}&latlng={1}&client={2}&signature={3}", "nl", "51.123456,5.612345", "gme-aa", "******_******=");

            byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            /*
             * Read HttpWeb Response
             */
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string Response = reader.ReadToEnd();
            response.Close();

EDIT:

I'm working inside Lowcode platform Outsystems. Outsystems creates the url inside WebRequest.Create() without the paramaters. So, I have access to webRequest object and need to pass the parameters.

You have to use HTTP "GET" Method.

In a GET request, you pass parameters as part of the query string.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://maps.googleapis.com/maps/api/geocode/json?language=fr&latlng=51.123456,5.612345&key={apiKey}");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
}

According the documentation , the API is expecting a POST method and receiving the parameters in the URL and not the body.

If you are using the OutSystems platform you can use the Consume REST API functionality to easily call the web service without using code. Configure your API like this (you can copy the example JSON from the documentation page above):

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM