"No file uploaded or URL provided" when calling ocr.space API
我想知道我们如何将文件上传到服务器,如上面的url所发送的那样,代码在C#中,但我希望它在Java for android
我的代码是
`final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("https://api.ocr.space/parse/image");
//httppost.addHeader("User-Agent", "Mozilla/5.0");
//httppost.addHeader("Accept-Language", "en-US,en;q=0.5");
//con.setRequestMethod("POST");
// con.setRequestProperty("User-Agent", "Mozilla/5.0");
// con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
final FileBody image = new FileBody(new File(fileName));
final MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("isOverlayRequired", new StringBody(Boolean.toString(isOverlayRequired)));
reqEntity.addPart("language", new StringBody(langCode));
reqEntity.addPart("apikey", new StringBody(apiKey));
reqEntity.addPart("file",image);
httppost.setEntity(reqEntity);
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity resEntity = response.getEntity();
final StringBuilder sb = new StringBuilder();
if (resEntity != null) {
final InputStream stream = resEntity.getContent();
byte bytes[] = new byte[4096];
int numBytes;
while ((numBytes=stream.read(bytes))!=-1) {
if (numBytes!=0) {
sb.append(new String(bytes, 0, numBytes));
}
}
}
Log.i("data", sb.toString());`
但它提供异常
javax.net.ssl.SSLException: hostname in certificate didn't match: <api.ocr.space> != <ocr.a9t9.com> OR <ocr.a9t9.com> OR <www.ocr.a9t9.com>
答案 0 :(得分:0)
您可以尝试给定的link
但是这个网站提供的例子是uri而不是文件。
试试这个适用于我的代码。
String charset = "UTF-8";
File uploadFile1 = new File(fileName);
String requestURL = "https://api.ocr.space/parse/image";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "Mozilla/5.0");
multipart.addHeaderField("Accept-Language", "en-US,en;q=0.5");
multipart.addFormField("apikey", apiKey);
multipart.addFormField("isOverlayRequired", Boolean.toString(isOverlayRequired));
multipart.addFormField("language", langCode);
multipart.addFilePart("file", uploadFile1);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}