我需要将相机手机拍摄的照片上传到名为IMAGGA的REST API。我在API's文档中找到了以下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"))
答案 0 :(得分:1)
要将图片发布到Imagga,请使用下面的postImageToImagga
方法。
待办事项:
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();