2

I am trying to upload photos to a web service from an Android app. I'm using the third-party library Retrofit to interact with the service.

I'm using a TypedByteArray as the body of my request, like so:

        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);

And the upload method interface looks like this:

    @POST("/image/upload")
    @Headers("Accept-Version: 2.0.0")
    void uploadRawImage(@Body TypedByteArray body, Callback<String> callback);

Sometimes this works, and sometimes it doesn't. I haven't been able to identify the pattern. It doesn't seem to be related to the specific image I try to upload, since has worked and failed with the same image. When it fails, I never get any response back, because the Retrofit request thread just hangs with the stack:

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   
...

This is driving me absolutely mad. If anyone has any ideas what could be wrong, or how to fix it, please help!

bryanspitz
  • 21
  • 2
  • Did you get an answer for this? Did you find any solution? I'm having a similar issue... http://stackoverflow.com/questions/25350724/uploading-a-file-over-ssl-w-client-side-certificate-and-androids-httpsurlconne?noredirect=1#comment39547346_25350724 – Felix Aug 19 '14 at 16:46

0 Answers0