2016-02-25 54 views
2

我想從我的C#應用​​程序調用該API時: https://ocr.space/OCRAPI「沒有文件上傳或網址提供的」調用API ocr.space

當我把它捲曲,它只是正常工作:

curl -k --form "[email protected]" --form "apikey=helloworld" --form "language=eng" https://api.ocr.space/Parse/Image 

我實現了這種方式:

[TestMethod] 
    public async Task Test_Curl_Call() 
    { 

     var client = new HttpClient(); 

     String cur_dir = Directory.GetCurrentDirectory(); 

     // Create the HttpContent for the form to be posted. 
     var requestContent = new FormUrlEncodedContent(new[] { 
       new KeyValuePair<string, string>( "file", "@filename.jpg"), //I also tried "filename.jpg" 
       new KeyValuePair<string, string>( "apikey", "helloworld"), 
     new KeyValuePair<string, string>("language", "eng")}); 

     // Get the response. 
     HttpResponseMessage response = await client.PostAsync(
      "https://api.ocr.space/Parse/Image", 
      requestContent); 

     // Get the response content. 
     HttpContent responseContent = response.Content; 

     // Get the stream of the content. 
     using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync())) 
     { 
      // Write the output. 
      String result = await reader.ReadToEndAsync(); 
      Console.WriteLine(result); 
     } 

    } 

我得到這樣的回答:

{ 
    "ParsedResults":null, 
    "OCRExitCode":99, 
    "IsErroredOnProcessing":true, 
    "ErrorMessage":"No file uploaded or URL provided", 
    "ErrorDetails":"", 
    "ProcessingTimeInMilliseconds":"0" 
} 

任何線索?

"[email protected]"中的@字符是什麼?

我把我的filename.jpg文件放在項目 test project bin/debug目錄下,並在調試模式下運行我的測試項目。

所以我不認爲錯誤指向的文件不在預期的位置。 我寧願懷疑我的代碼中有語法錯誤。

回答

3

的錯誤信息,告訴你什麼是錯的:

沒有文件上傳或網址提供

您發送一個文件名在代碼中的服務,但是這是不一樣的東西給捲曲文件名。 curl足夠聰明,可以讀取文件並將內容與您的請求一起上傳,但在您的C#代碼中,您必須自己做。步驟如下:

  1. 從磁盤讀取文件字節。
  2. 使用兩個部分創建多部分請求:API密鑰(「helloworld」)和文件字節。
  3. 將此請求發佈到API。

幸運的是,這很容易。 This question演示了設置多部分請求的語法。

此代碼爲我工作:

public async Task<string> TestOcrAsync(string filePath) 
{ 
    // Read the file bytes 
    var fileBytes = File.ReadAllBytes(filePath); 
    var fileName = Path.GetFileName(filePath); 

    // Set up the multipart request 
    var requestContent = new MultipartFormDataContent(); 

    // Add the demo API key ("helloworld") 
    requestContent.Add(new StringContent("helloworld"), "apikey"); 

    // Add the file content 
    var imageContent = new ByteArrayContent(fileBytes); 
    imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); 
    requestContent.Add(imageContent, "file", fileName); 

    // POST to the API 
    var client = new HttpClient(); 
    var response = await client.PostAsync("https://api.ocr.space/parse/image", requestContent); 

    return await response.Content.ReadAsStringAsync(); 
} 
+0

這就像一個魅力。我從中學到了很多,謝謝Nate。 –

+0

@AD沒問題! –

相關問題