Android使用OkHttp进行多部分文件上传

huangapple go评论68阅读模式
英文:

Android multipart file upload with OkHttp

问题

以下是使用OkHttp进行替换的代码:

import okhttp3.*;

public class HttpMultipartUpload {
    static String boundary = "AaB03x87yxdkjnxvi7";

    public static String upload(URL url, File file, String fileParameterName, HashMap<String, String> parameters)
            throws IOException {
        MediaType MEDIA_TYPE_XML = MediaType.parse("text/xml");
        OkHttpClient client = new OkHttpClient();

        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(fileParameterName, file.getName(), RequestBody.create(MEDIA_TYPE_XML, file));

        for (String name : parameters.keySet()) {
            requestBodyBuilder.addFormDataPart(name, parameters.get(name));
        }

        RequestBody requestBody = requestBodyBuilder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("Unexpected response code: " + response);
            }
        }
    }
}

这段代码使用了OkHttp库来执行与你之前的HttpURLConnection相同的任务。首先,它创建一个OkHttpClient实例,然后使用MultipartBody.Builder来构建多部分请求体,添加文件和参数。最后,它创建一个Request对象,并使用OkHttpClient来执行POST请求,并处理服务器的响应。注意,这段代码假设你已经添加了OkHttp库的依赖。

英文:

I am using this for audio records and video file and it is working but i want to replace it with OkHttp. I didnt figure it out. Can anyone help me about it?

public class HttpMultipartUpload {
    static String lineEnd = &quot;\r\n&quot;;
    static String twoHyphens = &quot;--&quot;;
    static String boundary = &quot;AaB03x87yxdkjnxvi7&quot;;

    public static String upload(URL url, File file, String fileParameterName, HashMap&lt;String, String&gt; parameters)
            throws IOException {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream dis = null;
        FileInputStream fileInputStream = null;

        byte[] buffer;
        int maxBufferSize = 20 * 1024;
        try {
            //------------------ CLIENT REQUEST
            fileInputStream = new FileInputStream(file);

            // open a URL connection to the Servlet
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don&#39;t use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod(&quot;POST&quot;);
            conn.setRequestProperty(&quot;Content-Type&quot;, &quot;multipart/form-data;boundary=&quot; + boundary);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes(&quot;Content-Disposition: form-data; name=\&quot;&quot; + fileParameterName
                    + &quot;\&quot;; filename=\&quot;&quot; + file.toString() + &quot;\&quot;&quot; + lineEnd);
            dos.writeBytes(&quot;Content-Type: text/xml&quot; + lineEnd);
            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            buffer = new byte[Math.min((int) file.length(), maxBufferSize)];
            int length;
            // read file and write it into form...
            while ((length = fileInputStream.read(buffer)) != -1) {
                dos.write(buffer, 0, length);
            }

            for (String name : parameters.keySet()) {
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes(&quot;Content-Disposition: form-data; name=\&quot;&quot; + name + &quot;\&quot;&quot; + lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(parameters.get(name));
            }

            // send multipart form data necessary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            dos.flush();
        } finally {
            if (fileInputStream != null) fileInputStream.close();
            if (dos != null) dos.close();
        }

        //------------------ read the SERVER RESPONSE
        try {
            dis = new DataInputStream(conn.getInputStream());
            StringBuilder response = new StringBuilder();

            String line;
            while ((line = dis.readLine()) != null) {
                response.append(line).append(&#39;\n&#39;);
            }

            return response.toString();
        } finally {
            if (dis != null) dis.close();
        }
    }
}

How can I change it with OkHttp. Any code please. I dont have good knowledge about on OkHttp. I was using (HttpURLConnection) but it seems not effective now.

答案1

得分: 3

请参考文档中的示例以发布表单数据:

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java

    RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "Square Logo")
        .addFormDataPart("image", "logo-square.png",
            RequestBody.create(
                new File("docs/images/logo-square.png"),
                MEDIA_TYPE_PNG))
        .build();

    Request request = new Request.Builder()
        .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
        .url("https://api.imgur.com/3/image")
        .post(requestBody)
        .build();
英文:

See the documentation example on posting form data

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java

    RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart(&quot;title&quot;, &quot;Square Logo&quot;)
        .addFormDataPart(&quot;image&quot;, &quot;logo-square.png&quot;,
            RequestBody.create(
                new File(&quot;docs/images/logo-square.png&quot;),
                MEDIA_TYPE_PNG))
        .build();

    Request request = new Request.Builder()
        .header(&quot;Authorization&quot;, &quot;Client-ID &quot; + IMGUR_CLIENT_ID)
        .url(&quot;https://api.imgur.com/3/image&quot;)
        .post(requestBody)
        .build();

huangapple
  • 本文由 发表于 2020年10月4日 22:03:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64195595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定