我正在尝试从 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);
有时这有效,有时则无效。我无法识别模式。它似乎与我尝试上传的特定图片无关,因为使用同一张图片已经成功并且失败了。当它失败时,我永远不会得到任何响应,因为改造请求线程只是挂在堆栈中:
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
...
这让我非常生气。如果有人有任何想法可能是错误的,或者如何解决它,请帮助!