Note: this answer is for ohtp 1.x / 2.x. For 3.x see this other answer .
The Multipart class from mimecraft encapsulates the entire HTTP body and can handle regular fields as follows:
Multipart m = new Multipart.Builder() .type(Multipart.Type.FORM) .addPart(new Part.Builder() .body("value") .contentDisposition("form-data; name=\"non_file_field\"") .build()) .addPart(new Part.Builder() .contentType("text/csv") .body(aFile) .contentDisposition("form-data; name=\"file_field\"; filename=\"file1\"") .build()) .build();
Take a look at multipart / form-data encoding examples to understand how you need to create parts.
When you have a Multipart object, all that remains to be done is to specify the correct Content-Type header and pass the body bytes to the request.
Since you seem to be working with the vH 2.0 OkHttp API, with which I have no experience, this is just an assumption code:
// You'll probably need to change the MediaType to use the Content-Type // from the multipart object Request.Body body = Request.Body.create( MediaType.parse(m.getHeaders().get("Content-Type")), out.toByteArray());
For OkHttp 1.5.4, here is the stripped-down code that I use, which is adapted from the sample snippet :
OkHttpClient client = new OkHttpClient(); OutputStream out = null; try { URL url = new URL("http://www.example.com"); HttpURLConnection connection = client.open(url); for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } connection.setRequestMethod("POST"); // Write the request. out = connection.getOutputStream(); multipart.writeBodyTo(out); out.close(); // Read the response. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected HTTP response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { // Clean up. try { if (out != null) out.close(); } catch (Exception e) { } }
ento May 21 '14 at 13:21 2014-05-21 13:21
source share