通过使用JSON的Multipart请求连接到Android中的REST服务

时间:2016-05-24 06:45:07

标签: android rest multipart image-upload

我正在尝试连接到一个REST服务,该服务接受一个json对象和一个图像并从图像中返回文本(在OCR之后)。

REST服务的documentation表明请求必须类似于:

xdebug.max_nesting_level=500

所以我提到this tutorial并修改了代码,当我运行代码时它会给我以下错误:

-----BOUNDARY
Content-Type: application/json

{"engine":"tesseract"}
-----BOUNDARY

-----BOUNDARY
Content-Disposition: attachment;
Content-Type: image/png
filename="attachment.txt".

PNGDATA.........
-----BOUNDARY

以下是 MultipartUtility.java 文件

的内容
W/System.err: java.io.IOException: unexpected end of stream on Connection{192.168.0.102:8080, proxy=DIRECT@ hostAddress=192.168.0.102 cipherSuite=none protocol=http/1.1} (recycle count=0)

我在 MainActivty.java 文件中使用了这个MultipartUtility:

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;

/**
 * For sending Multipart requests: modified for OCR
 *http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
 *
 */
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;


        boundary = "---BOUNDARY";

        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/related; boundary=" + boundary);
 //       httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
   //     httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     *
     */
    public void addFormField() {
        writer.append(boundary).append(LINE_FEED);
      //  writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
        //        .append(LINE_FEED);
        writer.append("Content-Type: application/json").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.append("{\"engine\":\"tesseract\"}").append(LINE_FEED);
        writer.append(boundary).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append(boundary).append(LINE_FEED);
        writer.append("Content-Disposition: attachment;")
                .append(LINE_FEED);
        writer.append("Content-Type: image/png").append(LINE_FEED);
        writer.append("filename="+fileName+".").append(LINE_FEED);
        writer.append(LINE_FEED);


    //adding png data here
        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(boundary).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     * @param name - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException {
        List<String> response = new ArrayList<>();

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

        writer.close();

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

        return response;
    }
}

我是Android开发的新手,我试着弄清楚如何在我的应用表单中使用这个REST网络服务最近2-3天,但我无法让它工作。

另外请告诉我是否有更好/更简单的方法在Android应用中使用this web服务。

感谢。

1 个答案:

答案 0 :(得分:0)

最好的方法是使用loopj库发送Http post请求并使用Gson库来解析响应。