Generated the code below by postman:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001");
RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"; filename=\"[object Object]\"\r\nContent-Type: false\r\n\r\n\r\n-----011000010111000001101001--");
Request request = new Request.Builder()
.url("http://foobar.com/newsfeed/photo")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001")
.addHeader("x-access-token", "MczCvMEbllNhGaMwEDnGXuQjrwBAYuYleFlgsUZDWRYbVaohpEGgofonYcvHsgPaTnbzHxCvJWalYFTY")
.addHeader("accept-language", "ru")
.build();
Response response = client.newCall(request).execute();
This request make a file on Server with 0 Kb size. and I couldn't put a file. So, I have to put a file like this:
RequestBody body = RequestBody.create(mediaType, new File(filename));
But I got TimeOutExaption.
How to put a file by this kind of Rest API?
I found a way to multipart file upload by Ion.
Ion.with(context).load(url).setHeader("x-access-token", token)
.setMultipartParameter("x-access-token", token)
.setMultipartContentType("multipart/form-data")
.setMultipartFile("image", "image/jpeg", file)
.asString().withResponse().setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
if (result != null)
onSuccess(result.getResult(), result.getHeaders().code());
}
});
Rest API:
Related
I use OKHTTP3 library to upload files to my http file server.
I found this code to do this and it works fine.
But I also want to just create a new folder without file.
Does anybody know how to create the request?
OkHttpClient client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username,password);
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/plain"), file))
.addFormDataPart("other_field", "other_field_value")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();
My Http File Server is in default configuration.
I didn't set up any script, because I don't understand the process(see on https://rejetto.com/wiki/index.php?title=HFS:_Event_scripts)
Thank you
I'm trying to upload a file to the server using multipart form.
Since API 23 Android has deprecated the Apache HTTP library.
I switched to using OkHttp to do my file uploads like so:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(name, fileName, requestBodyPart)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
And the requestBodyPart is:
requestBodyPart = new RequestBody() {
#Override
public MediaType contentType() {
return MediaType.parse(contentType);
}
#Override
public void writeTo(BufferedSink sink) throws IOException {
try {
if (sink.writeAll(Okio.source(inputStream)) == 0) {
throw new IOException("Empty File!");
}
} finally {
MiscUtils.closeCloseable(inputStream);
}
}
};
However, it seems like OkHttp is not that great when it comes to file uploads. Lots of timeouts and seems to be creating several layers of abstractions (sources and sinks) and has this AsyncTimeout that fires while the file data is still being written over the socket.
Are there any recommendations for doing Multipart File Uploads from Android that work with API 23 onwards. I know I can include the HTTP legacy library but since it was removed I would prefer not to do that. Or is there a way I can improve the performance of OkHttp?
This should work
String name = ...
File file = ...
MediaType mediaType = MediaType.parse(...)
OkHttpClient httpClient = ...
Request request = new Request.Builder()
.url(url)
.post(new MultipartBuilder().type(MultipartBuilder.FORM)
.addFormDataPart(name,
file.getName(),
RequestBody.create(mediaType, file))
.build())
.build();
try {
Response response = httpClient.newCall(request).execute();
} catch (IOException e) {
// handle error
}
I recently switched to OkHttp. After the switch, the code below does the upload.
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"qqfile\""),
RequestBody.create(
MediaType.parse(filename),
new File(filename)))
.build();
If you compare images, the second image has multipartFiles size = 0. It should be of size = 1. How to populate multipartHttpRequest correctly using OkHttp to make server accept successful upload?
Controller code
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;
#RequestMapping (
method = RequestMethod.POST,
value = "/upload",
produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"
)
public String upload(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
MultipartHttpServletRequest multipartHttpRequest =
WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
final List<MultipartFile> files = multipartHttpRequest.getFiles("qqfile");
if (files.isEmpty()) {
LOG.error("qqfile name missing in request or no file uploaded");
return some error code here
}
MultipartFile multipartFile = files.iterator().next();
//process file code below
}
return failure;
}
You can get a MultipartFile more easier:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(#RequestParam("qqfile") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
// ...
}
return "failure";
}
And then, with OkHttp:
RequestBody body = new MultipartBuilder()
.addFormDataPart("qqfile", filename, RequestBody.create(MediaType.parse("media/type"), new File(filename)))
.type(MultipartBuilder.FORM)
.build();
Request request = new Request.Builder()
.url("/path/to/your/upload")
.post(body)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
That worked fine to me.
Be careful with MediaType.parse(filename), you must pass a valid type like text/plain, application/json, application/xml...
Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
File file= new File(FILE_PATH + FILE_NAME);
requestBodyBuilder.addFormDataPart("file", FILE_NAME, RequestBody.create(MultipartBody.FORM, file));
fileVO.getOriginalFlnm()
you can omission this field.
And also you have to set 'MultipartHttpServletRequest' parameter AND consumes, produces in header
#PostMapping(path = "/save", consumes = "multipart/*", produces = "application/json;charset=utf-8")
public boolean CONTROLLER(MultipartHttpServletRequest request, #RequestParam Map<String, Object> param) {
boolean result = SERVICE.save(request, param);
return result;
}
How is it possible to append params to an OkHttp Request.builder?
//request
Request.Builder requestBuilder = new Request.Builder()
.url(url);
I've managed the add header but not params.
Here is a complete example on how to use okhttp to make post request (okhttp3).
To send data as form body
RequestBody formBody = new FormBody.Builder()
.add("param_a", "value_a")
.addEncoded("param_b", "value_b")
.build();
To send data as multipart body
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("fieldName", fileToUpload.getName(),RequestBody.create(MediaType.parse("application/octet-stream"), fileToUpload))
.build();
To send data as json body
RequestBody jsonBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
jsonObject.toString());
Now create request
Request request = new Request.Builder()
.addHeader("header_a", "value_a") // to add header data
.post(formBody) // for form data
.post(jsonBody) // for json data
.post(multipartBody) // for multipart data
.build();
Response response = client.newCall(request).execute();
** fileToUpload is a object of type java File
** client is a object of type OkHttpClient
Maybe you mean this:
HttpUrl url = new HttpUrl.Builder().scheme("http").host(HOST).port(PORT)
.addPathSegment("xxx").addPathSegment("xxx")
.addQueryParameter("id", "xxx")
.addQueryParameter("language", "xxx").build();
You can use this lib: https://github.com/square/mimecraft:
FormEncoding fe = new FormEncoding.Builder()
.add("name", "Lorem Ipsum")
.add("occupation", "Filler Text")
.build();
Multipart content:
Multipart m = new Multipart.Builder()
.addPart(new Part.Builder()
.contentType("image/png")
.body(new File("/foo/bar/baz.png"))
.build())
.addPart(new Part.Builder()
.contentType("text/plain")
.body("The quick brown fox jumps over the lazy dog.")
.build())
.build();
See here:
How to use OKHTTP to make a post request?
ild like to recode my project and use okHttp instead of the default HttpClient implemented in Android.
I've downloaded the latest source of the okhttp-main release.
Now ive found some examples how to create and build a POST Request.
Now my Problem. I want to create a RequestBody which keep several Data (Strings, Files, whatever) but i can't assign them directly.
Means that the RequestBuilder must go through different Loops where it get it's data added.
OkHTTPs RequestBody seems to need the data immediatly as listed in the example
https://github.com/square/okhttp/wiki/Recipes
When i want to try something like
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM);
for (Object aMData : dataClass.getData().entrySet()) {
Map.Entry mapEntry = (Map.Entry) aMData;
String keyValue = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
requestBody.addPart(keyValue, value);
}
for (DataPackage dataPackage : dataClass.getDataPackages()) {
requestBody.addPart("upfile[]", dataPackage.getFile());
}
requestBody.build();
it fails because build() itself create the RequestBody. Before it's just a MultipartBuilder(). If i try to force the type to RequestBody it wont compile/run.
So, what is the proper way adding thos data after creating a MultiPartBuilder and add DATA and Strings?
Uploading file in multipart using OkHttp
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
This worked for me using okHttp3:
OkHttpClient client = new OkHttpClient();
File file = new File(payload);
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "image.jpg",
RequestBody.create(MediaType.parse("image/jpg"), file))
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
I modified Dr. Enemy's answer:
MultipartBody.Builder builder =new MultipartBody.Builder().setType(MultipartBody.FORM);
for (Object aMData : dataClass.getData().entrySet()) {
Map.Entry mapEntry = (Map.Entry) aMData;
String keyValue = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
builder.addPart(keyValue, value);
}
for (DataPackage dataPackage : dataClass.getDataPackages()) {
builder.addPart("upfile[]", dataPackage.getFile());
}
Start adding the formDataPart to builder and at end create RequestBody
RequestBody requestBody = builder.build();
you can perform above actions with
compile 'com.squareup.okhttp3:okhttp:3.4.1'