OkHttp Upload byte Array Developed by android

Keywords: Mobile OkHttp Android Apache simulator

Recently, we are going to rebuild Android 9.0 compatibility for the old project. The previous app request was packaged package of org.apache.http.legacy.jar, which will not be accessible on the 9.0 simulator, so it needs to be rebuilt. My plan is to directly change the bottom of the package to okhttp, which is simple and fast.

Okhttp's get post postfile is available on the Internet, so I won't dwell on it; here's what you can't find on the Internet, okhttp uploads byte [];

okhttp encapsulates file upload and uploads only by passing in filepath, which is inconsistent with your usual needs:

Usually the most common upload is for pictures, often using image compression to reduce the size of uploaded files, and we have compressed the hope of uploading directly, rather than saving to the local and then uploading;

I Baidu this thing for a while, found that some people are also asking, but no one gave a plan, I have not used okhttp before, so I first read how others upload files to write, so I saw this article: http://www.cnblogs.com/whoislcj/p/5529827.html

After observation, I found this:

As you can see, the file upload operation of okhttp is controlled here. The method of writeTo is to write byte data to the server. Looking at the code in the article, you can see that the operation here is to read the local file, write buffer, and finally write.

As you can see, okhttp encapsulated upload is actually a direct byte [], but it encapsulates a layer, only let us pass the name of the file, the operation behind it is invisible, we want to pass off the ready-made byte [], just need to rewrite this method, write directly to byte []

So I wrote this method:

private   String okhttpPostFile_forBytes()
    {


        try {
            //Complete Request Address
            MultipartBody.Builder builder = new MultipartBody.Builder();
            //Set type
            builder.setType(MultipartBody.FORM);
            //Additional parameter
            for (NameValuePair item : params) {
                builder.addFormDataPart(item.key, item.value);
            }
            File file=null;
            builder.addFormDataPart("file", "imgs.jpg", createProgressRequestBody(            MediaType.parse("application/octet-stream"), file));
            //Create RequestBody
            RequestBody body = builder.build();
            //Create Request
            final Request request = new Request.Builder().url(mUrl).post(body).build();

            OkHttpClient mOkHttpClient = new OkHttpClient();
            final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);

            try
            {
                Response response  = call.execute();
                if (response.isSuccessful()) {
                    return response.body().string();
                }
                else
                {
                    Logger.e("rest", "okhttp-post-err:" + response.code());
                }
            }
            catch (Exception ex)
            {
                 ex.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

There are also the following methods:

public <T> RequestBody createProgressRequestBody(final MediaType contentType, final File file) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return contentType;
        }

        @Override
        public long contentLength() {
            if (mfileData!=null)
                return mfileData.length;
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source;
            try {
                if (mfileData!=null)
                {
                    source =Okio.source(new ByteArrayInputStream(mfileData));
                    Buffer buf = new Buffer();
                    long remaining = contentLength();
                    long current = 0;
                    for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                        sink.write(buf, readCount);
                        current += readCount;
                        //callback progress notification
                    }
                }
                else
                {
                    source = Okio.source(file);
                    Buffer buf = new Buffer();
                    long remaining = contentLength();
                    long current = 0;
                    for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                        sink.write(buf, readCount);
                        current += readCount;
                        //callback progress notification
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
}

After testing, it can be used and recorded.

Posted by vampke on Fri, 25 Jan 2019 18:00:14 -0800