2016-05-26 46 views
1

"No file uploaded or URL provided" when calling ocr.space API文件上載到ocr.space API

我想知道我們如何可以上傳文件到服務器在上面的URL發送,該代碼是C#,但我想它在Java中的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

嘿男人!你有沒有解決這個問題?你能提供解決方案嗎! – Yekatandilburg

回答

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); 
} 
+1

我已經試過這個網站,但是我不能上傳我的文件:( – Colthurling

+0

嗨!我得到了「錯誤.... java.io.IOException:服務器返回了非正常狀態:403」。您能否提供完整的例子,請! – Yekatandilburg

+0

有你檢查你的API密鑰? –

2

下面是我的主要代碼:

private String sendPost(boolean isOverlayRequired, File imageUrl, String language) throws Exception { 

     StringBuffer responseString = new StringBuffer(); 
     try { 
      MultipartUtility multipart = new MultipartUtility(url, "UTF-8"); 

      multipart.addFormField("isOverlayRequired", Boolean.toString(isOverlayRequired)); 
      multipart.addFilePart("file", imageUrl); 
      List<String> response = multipart.finish(); 

      for (String line : response) { 
       responseString.append(line); 
      } 
     } catch (IOException ex) { 
      Log.v("OCR Exception",ex.getMessage()); 
     } 

     //return result 
     return String.valueOf(responseString); 
    } 

API密鑰應添加到頭部。我已經在MultiPartUtility代碼本身中添加了。以下是我的代碼:

package com.example.ab00428268.virtualassistant.Utils; 

import android.util.Log; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 
import java.util.ArrayList; 
import java.util.List; 

public class MultipartUtility { 
private final String boundary; 
private static final String LINE_FEED = "\r\n"; 
private HttpURLConnection httpConn; 
private String charset; 
private OutputStream outputStream; 
private PrintWriter writer; 

/** 
* This constructor initializes a new HTTP POST request with content type 
* is set to multipart/form-data 
* @param requestURL 
* @param charset 
* @throws IOException 
*/ 
public MultipartUtility(String requestURL, String charset) 
     throws IOException { 
    this.charset = charset; 

    // creates a unique boundary based on time stamp 
    boundary = "===" + System.currentTimeMillis() + "==="; 

    URL url = new URL(requestURL); 
    httpConn = (HttpURLConnection) url.openConnection(); 
    httpConn.setUseCaches(false); 
    httpConn.setDoOutput(true); // indicates POST method 
    httpConn.setDoInput(true); 
    httpConn.setRequestProperty("Content-Type", 
      "multipart/form-data; boundary=" + boundary); 
    httpConn.setRequestProperty("User-Agent", "Mozilla/5.0"); 
    httpConn.setRequestProperty("apikey", "YourAPIKey"); 
    outputStream = httpConn.getOutputStream(); 
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), 
      true); 
    } 

    public void addFormField(String name, String value) { 
    writer.append("--" + boundary).append(LINE_FEED); 
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"") 
      .append(LINE_FEED); 
    writer.append("Content-Type: text/plain; charset=" + charset).append(
      LINE_FEED); 
    writer.append(LINE_FEED); 
    writer.append(value).append(LINE_FEED); 
    writer.flush(); 
    } 


    public void addFilePart(String fieldName, File uploadFile) 
     throws IOException { 
    String fileName = uploadFile.getName(); 
    writer.append("--" + boundary).append(LINE_FEED); 
    writer.append(
      "Content-Disposition: form-data; name=\"" + fieldName 
        + "\"; filename=\"" + fileName + "\"") 
      .append(LINE_FEED); 
    writer.append(
      "Content-Type: " 
        + URLConnection.guessContentTypeFromName(fileName)) 
      .append(LINE_FEED); 
    Log.v("MultiPart",fileName); 
    Log.v("MultiPart",uploadFile.getPath()); 
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 
    writer.append(LINE_FEED); 
    writer.flush(); 

    FileInputStream inputStream = new FileInputStream(uploadFile); 
    byte[] buffer = new byte[4096]; 
    int bytesRead = -1; 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outputStream.write(buffer, 0, bytesRead); 
    } 
    outputStream.flush(); 
    inputStream.close(); 

    writer.append(LINE_FEED); 
    writer.flush(); 
    } 


    public void addHeaderField(String name, String value) { 
    writer.append(name + ": " + value).append(LINE_FEED); 
    writer.flush(); 
    } 


    public List<String> finish() throws IOException { 
    List<String> response = new ArrayList<String>(); 

    writer.append(LINE_FEED).flush(); 
    writer.append("--" + boundary + "--").append(LINE_FEED); 
    writer.close(); 

    // checks server's status code first 
    int status = httpConn.getResponseCode(); 
    Log.v("MultiPart",""+httpConn.getResponseMessage()); 
    if (status == HttpURLConnection.HTTP_OK) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       httpConn.getInputStream())); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      Log.v("MultiPart",""+line); 
      response.add(line); 
     } 
     reader.close(); 
     httpConn.disconnect(); 
    } else { 
     throw new IOException("Server returned non-OK status: " + status); 
    } 

    return response; 
    } 
    }