{"id":7738,"date":"2015-10-19T01:17:20","date_gmt":"2015-10-19T01:17:20","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/10\/19\/how-to-use-okhttp-to-upload-a-file-open-source-projects-square-okhttp\/"},"modified":"2015-10-19T01:17:20","modified_gmt":"2015-10-19T01:17:20","slug":"how-to-use-okhttp-to-upload-a-file-open-source-projects-square-okhttp","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2015\/10\/19\/how-to-use-okhttp-to-upload-a-file-open-source-projects-square-okhttp\/","title":{"rendered":"how to use okhttp to upload a file?-open source projects square\/okhttp"},"content":{"rendered":"<p><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/3a722de9e052dd09c14ef0b8cf2d9456?s=128&amp;d=identicon&amp;r=PG\" \/> <strong>ento<\/strong><\/p>\n<p>The class <code>Multipart<\/code> from mimecraft encapsulates the whole HTTP body and can handle regular fields like so:<\/p>\n<pre><code>Multipart m = new Multipart.Builder()\n        .type(Multipart.Type.FORM)\n        .addPart(new Part.Builder()\n                .body(\"value\")\n                .contentDisposition(\"form-data; name=\\\"non_file_field\\\"\")\n                .build())\n        .addPart(new Part.Builder()\n                .contentType(\"text\/csv\")\n                .body(aFile)\n                .contentDisposition(\"form-data; name=\\\"file_field\\\"; filename=\\\"file1\\\"\")\n                .build())\n        .build();\n<\/code><\/pre>\n<p>Take a look at examples of multipart\/form-data encoding to get a sense of how you need to construct the parts.<\/p>\n<p>Once you have a <code>Multipart<\/code> object, all that&#8217;s left to do is specify the right <code>Content-Type<\/code> header and pass on the body bytes to the request.<\/p>\n<p>Since you seem to be working with the v2.0 of the OkHttp API, which I don&#8217;t have experience with, this is just guess code:<\/p>\n<pre><code>\/\/ You'll probably need to change the MediaType to use the Content-Type\n\/\/ from the multipart object\nRequest.Body body =  Request.Body.create(\n        MediaType.parse(m.getHeaders().get(\"Content-Type\")),\n        out.toByteArray());\n<\/code><\/pre>\n<p>For OkHttp 1.5.4, here is a stripped down code I&#8217;m using which is adapted from a sample snippet:<\/p>\n<pre><code>OkHttpClient client = new OkHttpClient();\nOutputStream out = null;\ntry {\n    URL url = new URL(\"http:\/\/www.example.com\");\n    HttpURLConnection connection = client.open(url);\n    for (Map.Entry entry : multipart.getHeaders().entrySet()) {\n        connection.addRequestProperty(entry.getKey(), entry.getValue());\n    }\n    connection.setRequestMethod(\"POST\");\n    \/\/ Write the request.\n    out = connection.getOutputStream();\n    multipart.writeBodyTo(out);\n    out.close();\n\n    \/\/ Read the response.\n    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {\n        throw new IOException(\"Unexpected HTTP response: \"\n                + connection.getResponseCode() + \" \" + connection.getResponseMessage());\n    }\n} finally {\n    \/\/ Clean up.\n    try {\n        if (out != null) out.close();\n    } catch (Exception e) {\n    }\n}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>ento The class Multipart from mimecraft encapsulates the whole HTTP body and can handle regular fields like so: Multipart m = new Multipart.Builder() .type(Multipart.Type.FORM) .addPart(new Part.Builder() .body(&#8220;value&#8221;) .contentDisposition(&#8220;form-data; name=\\&#8221;non_file_field\\&#8221;&#8221;) .build()) .addPart(new Part.Builder() .contentType(&#8220;text\/csv&#8221;) .body(aFile) .contentDisposition(&#8220;form-data; name=\\&#8221;file_field\\&#8221;; filename=\\&#8221;file1\\&#8221;&#8221;) .build()) .build(); Take a look at examples of multipart\/form-data encoding to get a sense of how you need [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-7738","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7738","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=7738"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7738\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=7738"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=7738"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=7738"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}