TransWikia.com

Tengo problemas al enviar mis credenciales y consumir una API

Stack Overflow en español Asked by Hector Ramos on March 6, 2021

Ya logre resolver mi duda sobre el token, ahora lo que tengo problemas es como puedo subir un file de formato txt que lo tengo guardado en mi disco D en una carpeta llamada SENDSUNATdoc.txt una vez que me devuelva eso, me genera un ticket al cual lo concateno y me devolverán 3 archivos xml, zip y excel que los quiero guardar en carpeta diferentes… Alguien me podría ayudar?

    //VARIABLES
    const string userName = "mi usuario";
    const string password = "mi clave";
    const string apiBaseUri = "https://ose-gw1.efact.pe:443";
    const string apiGetPeoplePath = "/api-efact-ose/oauth";
    const string authorization = "Y2xpZW50OnNlY3JldA==";
    const string tempurl = @"D:\SENDSUNAT\doc.txt";
    const string tempurl2 = "doc.txt";

    static void Main(string[] args)
    {
        //OBTENER EL TOKEN
        var token = GetAPIToken(userName, password, apiBaseUri).Result;
        Console.WriteLine("Token: {0}", token);

        //HACER EL LLAMADO
        var response = GetRequest(token, apiBaseUri, apiGetPeoplePath).Result;
        Console.WriteLine("response: {0}", response);

        //ESPERAR LA CLAVE
        Console.ReadKey();
    }

    private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
    {
        using (var client = new HttpClient())
        {
            //SETUP CLIENTE
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorization);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //SETUP LOGIN DATA
            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", password),
            });

            //ENVIAR REQUEST
            HttpResponseMessage response = await client.PostAsync("https://ose-gw1.efact.pe:443/api-efact-ose/oauth/token", formContent);


            //OBTENER EL ACCESO TOKEN DEL RESPONSE BODY
            var responseJson = await response.Content.ReadAsStringAsync();
            var jObject = JObject.Parse(responseJson);
            return jObject.GetValue("access_token").ToString();
        }
    }

    static async Task<string> GetRequest(string token, string apiBaseUri, string requestPath)
    {
        using (var client = new HttpClient())
        {
            //SETUP CLIENTE
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            //var cont = new MultipartFormDataContent();
            //cont.Add(new StreamContent(new MemoryStream()), "file", tempurl);

            //var cont = new MultipartFormDataContent();
            //var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(tempurl));
            //cont.Add(fileContent);

            //var cont = new ByteArrayContent(System.IO.File.ReadAllBytes(tempurl));
            //Stream fileStream = System.IO.File.OpenRead("D:\SENDSUNAT\" + tempurl2);

            //var cont = new MultipartFormDataContent();
            //cont.Add(new ByteArrayContent(File.ReadAllBytes(tempurl)));

            //var cont = new MultipartFormDataContent();

            var method = new MultipartFormDataContent();
            const string fileName = "D:\SENDSUNAT\doc.txt";
            var streamContent = new StreamContent(File.Open(fileName, FileMode.Open));
            method.Add(streamContent, "file");

            //HACER EL REQUEST
            HttpResponseMessage response = await client.PostAsync("https://ose-gw1.efact.pe:443/api-efact-ose/v1/document", method);
            var responseString = await response.Content.ReadAsStringAsync();
            return responseString;
        }
    }

One Answer

Te recomiendo usar la librería restsharp.

     // obtener tocken
     public string getToken(String sURL, String sUserName, String sPassword)
     {  String access_token = "";
         string clientId = "client";
         string clientSecret = "secret";
         string credentials = String.Format("{0}:{1}", clientId, clientSecret);
         RestClient restClient = new RestClient(sURL);
         RestRequest restRequest = new RestRequest("/oauth/token");
         restRequest.RequestFormat = DataFormat.Json;
         restRequest.Method = Method.POST;
         restRequest.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
         restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");
         restRequest.AddHeader("Accept", "application/json");
         restRequest.AddParameter("grant_type", "password");
         restRequest.AddParameter("username", sUserName);
         restRequest.AddParameter("password", sPassword);
         try {
             var response = restClient.Execute(restRequest);
             if (response.StatusCode == HttpStatusCode.BadRequest){
                 dynamic objError = new ExpandoObject();
                 objError = JsonConvert.DeserializeObject(response.Content);
                 access_token = "";
                 var error = objError.invalid_grant;
                 var error_description = objError.error_description;
                 MessageBox.Show(error + " - " + error_description, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             if (response.StatusCode == HttpStatusCode.Accepted || response.StatusCode == HttpStatusCode.OK){
                 dynamic objRpta = new ExpandoObject();
                 objRpta = JsonConvert.DeserializeObject(response.Content);
                 access_token = objRpta.access_token;
                 String token_type = objRpta.token_type;
                 int expires_in = objRpta.expires_in;
             }
         }
         catch(IOException e){
             MessageBox.Show(e.ToString(), "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         return access_token;
    }

    //send txt
    public string sendDocumentoTXT(String strAccesoToken, String strRutaDocumento, String strURL)
    {
        String strTicket = "";
        String code = "";
        RestClient restClient = new RestClient(strURL);
        RestRequest restRequest = new RestRequest("/v1/document");
        restRequest.RequestFormat = DataFormat.Json;
        restRequest.Method = Method.POST;

        restRequest.AddHeader("Authorization", "Bearer " + strAccesoToken);
        restRequest.AddHeader("Content-Type", "multipart/form-data");
        restRequest.AddHeader("Accept", "application/json");

        restRequest.AddFile("file", strRutaDocumento);

        var response = restClient.Execute(restRequest);

        dynamic objRptaTicket = new ExpandoObject();
        objRptaTicket = JsonConvert.DeserializeObject(response.Content);

        if (response.StatusCode == HttpStatusCode.OK){ 
            code = objRptaTicket.code;
            strTicket = objRptaTicket.description;
        }
        else{
            strEnvioDocCode = objRptaTicket.code;
            strEnvioDocTicket = objRptaTicket.description;
            MessageBox.Show(strEnvioDocCode + " " + strEnvioDocTicket, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        return strTicket;
    }

Answered by Juanka . on March 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP