How To Post Multi-part/form Images With String Parameter In Android
I have an API which has a payload body of type String. But has both json and image (multiparty/form) as part of the payload body. Something like this: json={jsonbody} image=@image
Solution 1:
You might need to encode the image to a String, then put that String into your request body.
If you are using volley, you can try this:
StringRequest stringRequest = newStringRequest(Request.Method.POST, URL, newResponse
.Listener<String>() {
@OverridepublicvoidonResponse(String response) {
Log.d(TAG, "onResponse() called with: response = [" + response + "]");
}
}, newResponse.ErrorListener() {
@OverridepublicvoidonErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse() called with: error = [" + error + "]");
}
}) {
@OverrideprotectedMap<String, String> getParams() throws AuthFailureError {
Map<String, String> params = newHashMap<>();
params.put("img", BASE64_IMG);
return params;
}
};
mRequestQueue.add(stringRequest);
Override getParams and put your params in your request.
You have to encode your image to a String, using Base64.
Solution 2:
you can use this library link is click here..
compile"cz.msebera.android:httpclient:4.4.1.2"
code for add image
protected String doInBackground(Void... params) {
Stringresult="";
try {
HttpClientclient=newDefaultHttpClient();
HttpPostpost=newHttpPost("your url");
post.setHeader("key", Key_for_XYZ);
MultipartEntityBuilderentityBuilder= MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody("id", id);
entityBuilder.addTextBody("name", fnm);
// file path.....
entityBuilder.addBinaryBody("uploaded_file", destination);
cz.msebera.android.httpclient.HttpEntityentity= entityBuilder.build();
post.setEntity(entity);
cz.msebera.android.httpclient.HttpResponseresponse= client.execute(post);
cz.msebera.android.httpclient.HttpEntityhttpEntity= response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.e("result", result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// make sure you had import this packages...
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.entity.mime.HttpMultipartMode;
import cz.msebera.android.httpclient.entity.mime.MultipartEntityBuilder;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.util.EntityUtils;
Post a Comment for "How To Post Multi-part/form Images With String Parameter In Android"