我试图从我的C#应用程序中调用此API: https://ocr.space/OCRAPI
当我从curl调用它时,它运行正常:
curl -k --form "file=@filename.jpg" --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"
}
有任何线索吗?
"file=@filename.jpg"
中的@字符是什么?
我将我的filename.jpg文件放在项目和测试项目bin / debug目录中,并以调试模式运行我的测试项目。
所以我不认为错误指向文件不在预期的位置。 我宁愿怀疑代码中存在语法错误。
答案 0 :(得分:3)
错误消息告诉您错误:
没有上传文件或提供网址
您在代码中向服务发送了一个文件名,但这与给curl文件名不同。 curl非常聪明,可以根据您的请求读取文件并上传内容,但是在您的C#代码中,您必须自己完成。步骤将是:
幸运的是,这很容易。 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();
}