I am using okhttp3 for upload image on server and i success in Upload image but i can not POST parameter with MultipartBody
my code is here..
File sourceFile = new File(sourceImageFile);
Log.logInfo("File...::::" + sourceFile + " : " + sourceFile.exists());
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
OkHttpClient client = App.getInstance().getOkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(KEY_ACCESS_TOKEN, accessToken)
.addFormDataPart(KEY_FILE, "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
.build();
Request request = new Request.Builder()
.url(URL_IMAGE_UPLOAD)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
I want to add "key" and "value" by POST Method in above code So how can i do.
As I learned before, see this link https://stackoverflow.com/a/34127008/6554840
In that passed member_id with its value.
So you are passing values with KEY_ACCESS_TOKEN is must be work.
.addFormDataPart(KEY_ACCESS_TOKEN, accessToken)
will work as post parameter.
I hope it will work.
Note: Must be your Web side is working.
Use this you have to create HashMap<String, String> this way and add it to Builder.
These are the Imports.
import okhttp3.OkHttpClient;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
Code:
// HashMap with Params
HashMap<String, String> params = new HashMap<>();
params.put( "Param1", "A" );
params.put( "Param2", "B" );
// Initialize Builder (not RequestBody)
FormBody.Builder builder = new FormBody.Builder();
// Add Params to Builder
for ( Map.Entry<String, String> entry : params.entrySet() ) {
builder.add( entry.getKey(), entry.getValue() );
}
// Create RequestBody
RequestBody formBody = builder.build();
// Create Request (same)
Request request = new Request.Builder()
.url( "url" )
.post( formBody )
.build();
Related
I have a asp.net web api url which accepts query string parameters but its actually a post request. I am trying to access the same url in android but not sure how to pass the query parameters. Any help will be appreciated as I am not an android developer basically.
Here is the snippet:
RequestBody formBody = new FormBody.Builder()
.add("email", mEmail.toLowerCase())
.add("password", mPassword)
.build();
//2. Bind the request Object
Request req = new Request.Builder()
.url(loginAPI).post(formBody)
.build();
Response response = client.newCall(req).execute();
This is the solution:
String loginAPI = "http://api.myapi.com/api/authentication?email="+mEmail.toLowerCase()+"&password="+mPassword;
RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request req = new Request.Builder()
.url(loginAPI)
.method("POST", reqbody)
.build();
Response response = client.newCall(req).execute();
I'm using OkHTTP for making a post request to my server. I know I can build a request like this:
RequestBody formBody = new FormEncodingBuilder()
.add("param1", param1)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
So what I want to do is to add the parameters dynamically. E.g:
RequestBody formBody = new FormEncodingBuilder()
for (ParamsArray m : requestParams) {
formBody.add("param1", requestParams.value);
}
But there's no function add for a RequestBody and I don't know if it is possible to convert a FormEncodingBuilder to a RequestBody.
Thank you!
A FormEncodingBuilder will turn into a RequestBody when you build it. Looking at the documentation, something like this ought to work.
FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder()
for (ParamsArray m : requestParams) {
formBodyBuilder.add("param1", requestParams.value);
}
RequestBody body = formBodyBuilder.build()
The documentation is available here:
https://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/FormEncodingBuilder.html
As of 3.0.0, the FormEncodingBuilder is gone:
Form and Multipart bodies are now modeled. We've replaced the opaque
FormEncodingBuilder with the more powerful FormBody and
FormBody.Builder combo. Similarly we've upgraded MultipartBuilder into
MultipartBody, MultipartBody.Part, and MultipartBody.Builder.
So replace with FormBody.Builder for these versions.
try this
FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
for (ParamsArray m : requestParams) {
formBodyBuilder.add("param1", requestParams.value);
}
RequestBody formBody = formBodyBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Instead of FormEncodingBuilder
use
Builder paramBuilder = new FormBody.Builder();
paramBuilder.add("param1","value1");
paramBuilder.add("param2","value2");
RequestBody requestBody = paramBuilder.build();
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'