Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use okhttp to upload a file?

I use okhttp to be my httpclient. I think it's a good api but the doc is not so detailed.

how to use it to make a http post request with file uploading?

public Multipart createMultiPart(File file){     Part part = (Part) new Part.Builder().contentType("").body(new File("1.png")).build();     //how to  set part name?     Multipart m = new Multipart.Builder().addPart(part).build();     return m; } public String postWithFiles(String url,Multipart m) throws  IOException{     ByteArrayOutputStream out = new ByteArrayOutputStream();     m.writeBodyTo(out)     ;     Request.Body body =  Request.Body.create(MediaType.parse("application/x-www-form-urlencoded"),             out.toByteArray());      Request req = new Request.Builder().url(url).post(body).build();     return client.newCall(req).execute().body().string();  } 

my question is:

  1. how to set part name? in the form, the file should be named file1.
  2. how to add other fields in the form?
like image 893
user2219372 Avatar asked May 07 '14 08:05

user2219372


People also ask

What is the use of OkHttp?

OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.


1 Answers

Here is a basic function that uses okhttp to upload a file and some arbitrary field (it literally simulates a regular HTML form submission)

Change the mime type to match your file (here I am assuming .csv) or make it a parameter to the function if you are going to upload different file types

  public static Boolean uploadFile(String serverURL, File file) {     try {          RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)                 .addFormDataPart("file", file.getName(),                         RequestBody.create(MediaType.parse("text/csv"), file))                 .addFormDataPart("some-field", "some-value")                 .build();          Request request = new Request.Builder()                 .url(serverURL)                 .post(requestBody)                 .build();          client.newCall(request).enqueue(new Callback() {              @Override             public void onFailure(final Call call, final IOException e) {                 // Handle the error             }              @Override             public void onResponse(final Call call, final Response response) throws IOException {                 if (!response.isSuccessful()) {                     // Handle the error                 }                 // Upload successful             }         });          return true;     } catch (Exception ex) {         // Handle the error     }     return false; } 

Note: because it is async call, the boolean return type does not indicate successful upload but only that the request was submitted to okhttp queue.

like image 136
iTech Avatar answered Sep 28 '22 08:09

iTech