在 Android Studio 中使用 HttpURLConnection 上传图像(到 IMAGGA)

Upload image (to IMAGGA) using HttpURLConnection in Android Studio

我需要将相机手机拍摄的照片上传到名为 IMAGGA. I found in the API's 的 REST API 文档,以下 Java 代码:

String apiKey = "",
apiSecret = "";


 HttpResponse response = Unirest.post("https://api.imagga.com/v1/content")
.basicAuth(apiKey, apiSecret)
.field("image", new File("/path/to/image.jpg"))
.asJson();

JSONObject jsonResponse = response.getBody().getObject();
System.out.println(jsonResponse.toString());

此代码为我提供了一个标识符,因此我可以使用它从图像标记中获取 json。

我无法完成它,因为我正在使用 HttpURLConnection,但我不知道该怎么做。

我唯一遇到的问题是上传部分:

.field("image", new File("/path/to/image.jpg"))

要post一张图片到Imagga,使用下面的postImageToImagga方法。

待办事项:

  1. 请在 Imagga 仪表板的代码中插入您自己的基本授权详细信息,请参阅代码中的以下行:connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");

public String postImageToImagga(String filepath) throws Exception {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary =  "*****"+Long.toString(System.currentTimeMillis())+"*****";
    String lineEnd = "\r\n";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    String filefield = "image";

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    File file = new File(filepath);
    FileInputStream fileInputStream = new FileInputStream(file);

    URL url = new URL("https://api.imagga.com/v1/content");
    connection = (HttpURLConnection) url.openConnection();

    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
    connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
    outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
    outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    while(bytesRead > 0) {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    inputStream = connection.getInputStream();

    int status = connection.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        inputStream.close();
        connection.disconnect();
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();

        return response.toString();
    } else {
       throw new Exception("Non ok response returned");
    }
}

要在非UI线程上调用上述代码,我们可以使用AsyncTask:

public class PostImageToImaggaAsync extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            String response = postImageToImagga("/mnt/sdcard/Pictures/Stone.jpg");
            Log.i("imagga", response);
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
    }
}

调用上面的PostImageToImaggaAsync代码:

PostImageToImaggaAsync postImageToImaggaAsync = new PostImageToImaggaAsync();
postImageToImaggaAsync.execute();