-3

I have a problem with the API in a console. So I want to post and I always get 411 error or 403. This is my code:

            string IntId = "suli";
            var lekeres = WebRequest.Create("https://xxxx.e-kreta.hu/idp/api/v1/Token") as HttpWebRequest;
            lekeres.Method = "POST";
            string adatokkal = "institute_code=" + IntId + "&userName=" + azonosito + "&password=" + jelszo + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";
            lekeres.Headers.Add(HttpRequestHeader.Authorization,adatokkal);
            var response = lekeres.GetResponse() as HttpWebResponse;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                Console.WriteLine(responseFromServer);
            }

The origin Curl command (It works):

curl --data "institute_code=xxxxxxxxx&userName=xxxxxxxxxxx&password=xxxxxxxxxxx&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56" https://xxxxxxxxxxx.e-kreta.hu/idp/api/v1/Token

Thanks for your help!

FloodXツ
  • 9
  • 1
  • 3
  • Well, I see as an issue is you are setting the authorization as your data... not sure why.. try: https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request – Trey Apr 12 '19 at 18:26
  • @esqew "--data" (or "-d") means POST to my understanding (https://stackoverflow.com/questions/42081299/curl-whats-the-difference-between-d-and-data-binary-options, https://curl.haxx.se/docs/manual.html)... Why do you think otherwise? – Alexei Levenkov Apr 12 '19 at 18:34
  • @esqew what would lead you to believe it's *not* supposed to be a POST request? OP specifically says the curl POST works, so I will believe it because it doesn't make any sense not to. – p e p Apr 12 '19 at 18:35
  • 1
    My misunderstanding re: the cURL structure & HTTP verb; removed my comment regarding it. – esqew Apr 12 '19 at 18:36
  • @esqew ah makes sense, thanks for clarifying that it was a misunderstanding! – p e p Apr 12 '19 at 18:37
  • @FloodX - the problem is you are trying to send the POST body as an `Authorization` header. To create the equivalent `HttpWebRequest` as a `curl -d ...` call, you need to add a request body. Follow this example on how to do that. From the example, just replace the `postData` string w/ your value. https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-send-data-using-the-webrequest-class#example – p e p Apr 12 '19 at 18:41

2 Answers2

0

You could always just use a Webclient:

                using (WebClient client = new WebClient())
                {
                    string adatokkal = "https://xxxx.e-kreta.hu/idp/api/v1/Token?institute_code=" + IntId + "&userName=" + azonosito + "&password=" + jelszo + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";
                    string Response = client.DownloadString(new Uri(AH_Data_Url));
                }

Or a HTTP client

            var client = new HttpClient
            {
                BaseAddress = new Uri("https://xxxx.e-kreta.hu")
            };
            var request = new HttpRequestMessage(HttpMethod.Post, "/idp/api/v1/Token");

            var formData = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("institute_code", IntId )
                new KeyValuePair<string, string>("userName", azonosito  )
                // Add the rest here
            };


            request.Content = new FormUrlEncodedContent(formData);
            var response = client.SendAsync(request).Result;

            if (response.IsSuccessStatusCode == true)
            {
                var responseContent = response.Content;
                string responsestring = responseContent.ReadAsStringAsync().Result;
            }
            else
            {

            }

If you have to authorize your request you should add something like

        var byteArray = new UTF8Encoding().GetBytes("Client ID" + ":" + "Client Secret");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Kalerion
  • 91
  • 1
  • 5
0

Since your curl -d (just a simple POST) works, you need to write your data to the request body, not the Authorization header as you have it. I think this should do it:

string IntId = "suli";
var lekeres = WebRequest.Create("https://xxxx.e-kreta.hu/idp/api/v1/Token") as HttpWebRequest;
lekeres.Method = "POST";
string adatokkal = "institute_code=" + IntId + "&userName=" + azonosito + "&password=" + jelszo + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";
 byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Set the ContentType property of the WebRequest.  
lekeres.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.  
lekeres.ContentLength = byteArray.Length;

// Get the request stream.  
Stream dataStream = lekeres.GetRequestStream();
// Write the data to the request stream.  
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.  
dataStream.Close();
var response = lekeres.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
    Console.WriteLine(responseFromServer);
}
p e p
  • 6,593
  • 2
  • 23
  • 32
  • This answer makes no assumptions about your ability to use other APIs than `HttpWebRequest`. That said, I'd personally prefer @Kalerion's answer suggesting to use a different type to create your http request (RestClient from [RestSharp](https://www.nuget.org/packages/RestSharp) is my go to, but HttpClient also works). Note that @Kalerion's top answer is wrong as it is a `GET` request, but their bottom example using `HttpClient` using a POST should work I believe. – p e p Apr 12 '19 at 18:47