N
N
NoLimits2020-11-14 23:23:19
C++ / C#
NoLimits, 2020-11-14 23:23:19

How to fix request error on Qiwi Api?

I can’t understand why, when sending a POST JSON request to Qiwi, it gives an error 400, I’ve been racking my brain for an hour now.
The code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://edge.qiwi.com/sinap/api/v2/terms/99/payments");
            request.Method = "POST";
            request.Headers["authorization"] = "Bearer " + token;
            request.ContentType = "application/json; charset=utf-8";
            string sQueryString = json;
            byte[] ByteArr = Encoding.ASCII.GetBytes(sQueryString);
            request.ContentLength = ByteArr.Length;
            request.GetRequestStream().Write(ByteArr, 0, ByteArr.Length);

            string html = string.Empty;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    html = myStreamReader.ReadToEnd();
                    MessageBox.Show(html);
                }
            }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2020-11-15
@vabka

1. Use HttpClient instead of WebRequest
2. Authorization capitalized
3. not ASCII, but utf-8
4. not html is returned, but a json object
5. Read the documentation
6. If an error occurs, then the response body will say that for a mistake

Code example

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;

var json = new
{
    id = "11111111111111",
    sum = new {amount = 100, currency = "643"},
    paymentMethod = new {type = "Account", accountId = "643"},
    comment = "test",
    fields = new {account = "+79121112233"}
};
var token = "YUu2qw048gtdsvlk3iu";

using var httpClient = new HttpClient();
using var request = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://edge.qiwi.com/sinap/api/v2/terms/99/payments"),
    Headers =
    {
        Accept = {MediaTypeWithQualityHeaderValue.Parse("application/json")},
        Authorization = AuthenticationHeaderValue.Parse("Bearer " + token)
    },
    Content = new StringContent(JsonSerializer.Serialize(json))
    {
        Headers = {ContentType = MediaTypeHeaderValue.Parse("application/json")}
    }
};

var response = await httpClient.SendAsync(request);
var responseText = await response.Content.ReadAsStringAsync();

Console.WriteLine(responseText);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question