Remote server returned an error: (400) Incorrect Request

Asked

Viewed 1,598 times

2

I created two methods, one for authentication via A1 and A3 type certificate and one for sending an xml, both of which request a client’s Rest api.

In the authentication method, I send my certificate data to the customer and have the return of a "Set-Token" with user information, "X-CSRF-Token" CSRF Attack Prevention Token and "X-CSRF-Expiration" with the expiration date.

Method of authentication.

public void CarregaCertificado()
        {

            string destinationUrl = "https://val.portalunico.siscomex.gov.br/portal/api/autenticar";
            string requestXml = "Aqui é a string do xml";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);

            X509Certificate2 oCertificado;
            var oX509Cert = new X509Certificate2();
            var store = new X509Store("MY", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            var collection = store.Certificates;

            var collection2 = collection.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);
            var scollection = X509Certificate2UI.SelectFromCollection(collection2,
              "Certificado(s) Digital(is) disponível(is)", "Selecione o certificado digital para uso no aplicativo",
               X509SelectionFlag.SingleSelection);


            if (scollection.Count == 0)
            {
                var msgResultado =
                    "Nenhum certificado digital foi selecionado ou o certificado selecionado está com problemas.";
                MessageBox.Show(msgResultado, "Advertência", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                oX509Cert = scollection[0];
                oCertificado = oX509Cert;
                request.ClientCertificates.Add(oCertificado);


                request.ContentType = "application/json";
                request.Headers.Add("Role-Type", "DEPOSIT");

                request.Method = "POST";

                HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse();

                string tokenResponse = string.Empty;
                string csrfTokenResponse = string.Empty;
                string csrfExpirionResponse = string.Empty;
                string keepAlive = string.Empty;
                string connection = string.Empty;
                string contentLength = string.Empty;
                string contentType = string.Empty;
                string date = string.Empty;
                string server = string.Empty;


                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream responseStream = response.GetResponseStream();

                    tokenResponse = response.Headers["Set-Token"];
                    csrfTokenResponse = response.Headers["X-CSRF-Token"];
                    csrfExpirionResponse = response.Headers["X-CSRF-Expiration"];
                    keepAlive = response.Headers["Keep-Alive"];
                    connection = response.Headers["Connection"];
                    contentLength = response.Headers["Content-Length"];
                    contentType = response.Headers["Content-Type"];
                    date = response.Headers["Date"];
                    server = response.Headers["Server"];



                    string responseStr = new StreamReader(responseStream).ReadToEnd();

                }

               EnvioXML(requestXml, tokenResponse, csrfTokenResponse, csrfExpirionResponse);

            }
        }

Recebo os dados após autenticação sem problemas!
Depois tento enviar o xml.
Método de envio do xml.

 public void EnvioXML(string requestXml, string tokenResponse, string csrfTokenResponse, string csrfExpirionResponse)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://val.portalunico.siscomex.gov.br/cct/api/ext/carga/entrega-conteiner");
            byte[] bytes;
            bytes = System.Text.Encoding.UTF8.GetBytes(requestXml);

            request.ContentType = "application/xml";

            request.Headers.Add("Authorization", tokenResponse);

            request.Headers.Add("X-CSRF-Token", csrfTokenResponse);           

            request.ContentLength = bytes.Length;

            request.ContentLength = 1;
            request.SendChunked = true;
            request.Method = "POST";           

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Stream responseStream1 = response.GetResponseStream();
                    }
                }
            }
            catch (WebException e)
            {

                MessageBox.Show(e.Message);
            }

        }
  • Please guys, somebody help me!

  • Have you used Fiddler to see exactly what is sending to the server?

  • I do not know the Fiddler, but I used the Postman but I have the same return.

  • In this case you are actually mounting the post incorrectly.

1 answer

1

Here is an example of sending code in visual basic.

' Variaveis
Dim cSiteDUE                As String
Dim objHTTP                 As New XMLHTTP
Dim cToken                  As String
Dim cCSRF                   As String
Dim objDom                  As New DOMDocument
Dim lTesteXML               As Integer
Dim cXML                    As String

' Autenticacao
On Error Resume Next
cSiteDUE = "https://val.portalunico.siscomex.gov.br/portal/api/autenticar"
objHTTP.open "POST", cSiteDUE, False
objHTTP.setRequestHeader "Role-Type", "IMPEXP"
objHTTP.send
If (Err) Then
    MsgBox Error, vbInformation, "Mensagem"
    Exit Sub
End If

' Leitura das Informacoes
' cRetorno = objHTTP.responseText
If (Err) Then
    MsgBox Error, vbInformation, "Mensagem"
    Exit Sub
End If
cToken = objHTTP.getResponseHeader("Set-Token")
cCSRF = objHTTP.getResponseHeader("X-CSRF-Token")

' Leitura do XML
lTesteXML = objDom.loadXML("c:\due\teste1.xml")

On Error Resume Next
Close #1
Open "c:\due\teste1.xml" For Input As #1
If (Err) Then
    MsgBox Error, vbInformation, "Mensagem"
    On Error GoTo 0
    Exit Sub
End If

On Error GoTo 0

' Looping de Leitura
cXML = ""
Do While Not EOF(1)

    ' Leitura da Linha
    Line Input #1, cLinha

    ' Processo
    cXML = cXML & Trim(cLinha)


Loop


' Envio da DU-e
cSiteDUE = "https://val.portalunico.siscomex.gov.br/due/api/ext/due"
objHTTP.open "POST", cSiteDUE, False
objHTTP.setRequestHeader "Content-Type", "application/xml"
objHTTP.setRequestHeader "Authorization", cToken
objHTTP.setRequestHeader "X-CSRF-Token", cCSRF
objHTTP.send cXML
If (Err) Then
    MsgBox Error, vbInformation, "Mensagem"
    Exit Sub
End If

' Leitura das Informacoes
cRetorno = objHTTP.responseText
If (Err) Then
    MsgBox Error, vbInformation, "Mensagem"
    Exit Sub
End If
MsgBox cRetorno
  • This procedure is sending and receiving the information correctly.

  • I managed to send Xml, the problem was in Xml.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.