2016-02-25 53 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没问题! –

相关问题