我正在尝试从Android应用上传照片到网络服务。我正在使用第三方库Retrofit与服务进行交互。
我正在使用TypedByteArray作为我的请求的主体,如下所示:
String contentType = String.format(Locale.US, "multipart/form-data; boundary=%s", BOUNDARY);
ByteArrayOutputStream os = new ByteArrayOutputStream();
StringBuilder prefix = new StringBuilder();
prefix.append("--").append(BOUNDARY).append("\r\n");
prefix.append("Content-Disposition: form-data; name=\"rawimage\"; filename=\"picture.jpg\"\r\n");
prefix.append("Content-Type: image/jpg\r\n\r\n");
byte[] buffer = prefix.toString().getBytes("UTF-8");
os.write(buffer);
boolean success = bitmap.compress(CompressFormat.JPEG, 50, os);
if (!success) {
Log.e(LOG_TAG, "Could not write image to request");
}
String suffix = String.format(Locale.US, "\r\n--%s--\r\n", BOUNDARY);
buffer = suffix.getBytes("UTF-8");
os.write(buffer);
byte[] body = os.toByteArray();
TypedByteArray myBody = new TypedByteArray(contentType, body);
上传方法界面如下所示:
@POST("/image/upload")
@Headers("Accept-Version: 2.0.0")
void uploadRawImage(@Body TypedByteArray body, Callback<String> callback);
有时候这种方法有效,有时则不然。我无法确定模式。它似乎与我尝试上传的特定图像无关,因为它已经工作并且失败了相同的图像。当它失败时,我永远不会得到任何回复,因为Retrofit请求线程只是挂起堆栈:
NativeCrypto.SSL_write(long, FileDescriptor, NativeCrypto$SSLHandshakeCallbacks, byte[], int, int, int) line: not available [native method]
OpenSSLSocketImpl$SSLOutputStream.write(byte[], int, int) line: 728
FixedLengthOutputStream.write(byte[], int, int) line: 41
FixedLengthOutputStream(OutputStream).write(byte[]) line: 82
TypedByteArray.writeTo(OutputStream) line: 66
UrlConnectionClient.prepareRequest(HttpURLConnection, Request) line: 89
UrlConnectionClient.execute(Request) line: 48
...
这让我非常生气。如果有人有任何想法可能是错误的,或者如何解决它,请帮助!