MicrosoftDocs / azure-docs

Open source documentation of Microsoft Azure
https://docs.microsoft.com/azure
Creative Commons Attribution 4.0 International
10.26k stars 21.43k forks source link

Error Uri #59724

Closed jaimegonzalezsicma closed 4 years ago

jaimegonzalezsicma commented 4 years ago

When implementing the example I get the following error: An invalid request URI was provided. The request URI must be an absolute URI or BaseAddress must be set

I think the code is not up to date


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

jaimegonzalezsicma commented 4 years ago

The code is from ths page https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/csharp-print-text

NavtejSaini-MSFT commented 4 years ago

@jaimegonzalezsicma We are checking this and will get back to you

RohitMungi-MSFT commented 4 years ago

@jaimegonzalezsicma Based on the error seen It looks like the uriBase is not formed correctly as the endpoint variable might not be set from the environment variable. You can try to use the endpoint or 'subscriptionKey` directly in the code and check if the sample works.

        static string subscriptionKey = "COMPUTER_VISION_SUBSCRIPTION_KEY";

        static string endpoint = "COMPUTER_VISION_ENDPOINT";

You can also create the environment variables as mentioned and check again

jaimegonzalezsicma commented 4 years ago

@RohitMungi-MSFT It keeps throwing error, if I write the endpoint directly it tells me: "Error sending the request".

I attach my code

using Newtonsoft.Json.Linq; using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks;`

namespace OCR_Test_2017 { static class Program { // Add your Computer Vision subscription key and endpoint to your environment variables. static string subscriptionKey = Environment.GetEnvironmentVariable("adsdasd");

    //static string endpoint = Environment.GetEnvironmentVariable("https://pldmexicotest.cognitiveservices.azure.com/");

    // the OCR method endpoint
    //static string uriBase = endpoint + "vision/v3/ocr";

    public static void Main()
    {
        MainAsync().GetAwaiter().GetResult();
    }
    static async Task MainAsync()
    {
        // Get the path and filename to process from the user.
        Console.WriteLine("Optical Character Recognition:");
        Console.Write("Enter the path to an image with text you wish to read: ");
        string imageFilePath = Console.ReadLine();

        if (File.Exists(imageFilePath))
        {
            // Call the REST API method.
            Console.WriteLine("\nWait a moment for the results to appear.\n");
            await MakeOCRRequest(imageFilePath);
        }
        else
        {
            Console.WriteLine("\nInvalid file path");
        }
        Console.WriteLine("\nPress Enter to exit...");
        Console.ReadLine();
    }

    /// <summary>
    /// Gets the text visible in the specified image file by using
    /// the Computer Vision REST API.
    /// </summary>
    /// <param name="imageFilePath">The image file with printed text.</param>
    static async Task MakeOCRRequest(string imageFilePath)
    {
        try
        {
            HttpClient client = new HttpClient();

            // Request headers.
            client.DefaultRequestHeaders.Add(
                "Ocp-Apim-Subscription-Key", subscriptionKey);

            // Request parameters. 
            // The language parameter doesn't specify a language, so the 
            // method detects it automatically.
            // The detectOrientation parameter is set to true, so the method detects and
            // and corrects text orientation before detecting text.
            string requestParameters = "language=unk&detectOrientation=true";

            // Assemble the URI for the REST API method.

            string uriBase = Environment.GetEnvironmentVariable("https://pldmexicotest.cognitiveservices.azure.com/") + "vision/v3/ocr";
            string uri = uriBase + "?" + requestParameters;

            HttpResponseMessage response;

            // Read the contents of the specified local image
            // into a byte array.
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            // Add the byte array as an octet stream to the request body.
            using (ByteArrayContent content = new ByteArrayContent(byteData))
            {
                // This example uses the "application/octet-stream" content type.
                // The other content types you can use are "application/json"
                // and "multipart/form-data".
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                // Asynchronously call the REST API method.
                response =  await client.PostAsync(uri, content);
                //HttpClient http = new HttpClient();
                //response = await http.GetByteArrayAsync(uri);
            }

            // Asynchronously get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();

            // Display the JSON response.
            Console.WriteLine("\nResponse:\n\n{0}\n",
                JToken.Parse(contentString).ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("\n" + e.Message);
        }
    }

    /// <summary>
    /// Returns the contents of the specified file as a byte array.
    /// </summary>
    /// <param name="imageFilePath">The image file to read.</param>
    /// <returns>The byte array of the image data.</returns>
    static byte[] GetImageAsByteArray(string imageFilePath)
    {
        // Open a read-only file stream for the specified file.
        using (FileStream fileStream =
            new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        {
            // Read the file's contents into a byte array.
            BinaryReader binaryReader = new BinaryReader(fileStream);
            return binaryReader.ReadBytes((int)fileStream.Length);
        }
    }
}

}

jaimegonzalezsicma commented 4 years ago

The error appears when writing the path of an image on my computer, if I type the url of a Google image it sends the error Invalid file path: C:\Temp\recibo-cfe-plantilla.jpg https://slideplayer.es/slide/5540498/2/images/1/El+p%C3%A1rrafo+Es+una+unidad+de+discurso+en+texto+escrito+que+expresa+una+idea+o+un+argumento%2C+o+reproduce+las+palabras+de+un+orador..jpg

jaimegonzalezsicma commented 4 years ago

I already solved it, I changed the EndPoint from https to http, but Azure tells me that it is with https, something strange is happening ...

using Newtonsoft.Json.Linq; using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks;

namespace OCR_Test_2017 { static class Program { public static void Main() { MainAsync().GetAwaiter().GetResult(); } static async Task MainAsync() { // Get the path and filename to process from the user. Console.WriteLine("Optical Character Recognition:"); Console.Write("Enter the path to an image with text you wish to read: "); string imageFilePath = Console.ReadLine();

        if (File.Exists(imageFilePath))
        {
            // Call the REST API method.
            Console.WriteLine("\nWait a moment for the results to appear.\n");
            await MakeOCRRequest(imageFilePath);
        }
        else
        {
            Console.WriteLine("\nInvalid file path");
        }
        Console.WriteLine("\nPress Enter to exit...");
        Console.ReadLine();
    }

    /// <summary>
    /// Gets the text visible in the specified image file by using
    /// the Computer Vision REST API.
    /// </summary>
    /// <param name="imageFilePath">The image file with printed text.</param>
    static async Task MakeOCRRequest(string imageFilePath)
    {
        try
        {
            HttpClient client = new HttpClient();

            // Request headers.
            // Add your Computer Vision subscription key and endpoint to your environment variables.
            client.DefaultRequestHeaders.Add(
                "Ocp-Apim-Subscription-Key", "4c5675f3a1d74d3d801ba3f9086bf5c7");

            // Request parameters. 
            // The language parameter doesn't specify a language, so the 
            // method detects it automatically.
            // The detectOrientation parameter is set to true, so the method detects and
            // and corrects text orientation before detecting text.
            string requestParameters = "language=unk&detectOrientation=true";

            // Assemble the URI for the REST API method.

            string uriBase = "http://pldmexicotest.cognitiveservices.azure.com/vision/v3.0/ocr";
            string uri = uriBase + "?" + requestParameters;

            HttpResponseMessage response;

            // Read the contents of the specified local image
            // into a byte array.
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            // Add the byte array as an octet stream to the request body.
            using (ByteArrayContent content = new ByteArrayContent(byteData))
            {
                // This example uses the "application/octet-stream" content type.
                // The other content types you can use are "application/json"
                // and "multipart/form-data".
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                // Asynchronously call the REST API method.
                response =  await client.PostAsync(uri, content);
            }

            // Asynchronously get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();

            // Display the JSON response.
            Console.WriteLine("\nResponse:\n\n{0}\n",
                JToken.Parse(contentString).ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("\n" + e.Message);
        }
    }

    /// <summary>
    /// Returns the contents of the specified file as a byte array.
    /// </summary>
    /// <param name="imageFilePath">The image file to read.</param>
    /// <returns>The byte array of the image data.</returns>
    static byte[] GetImageAsByteArray(string imageFilePath)
    {
        // Open a read-only file stream for the specified file.
        using (FileStream fileStream =
            new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        {
            // Read the file's contents into a byte array.
            BinaryReader binaryReader = new BinaryReader(fileStream);
            return binaryReader.ReadBytes((int)fileStream.Length);
        }
    }
}

}

RohitMungi-MSFT commented 4 years ago

@jaimegonzalezsicma You are using the variable incorrectly. As i mentioned in my first response please use the key as below instead of pasting the key in place of the environment variable

        static string subscriptionKey = "COMPUTER_VISION_SUBSCRIPTION_KEY";

        static string endpoint = "COMPUTER_VISION_ENDPOINT";