I\'m sharing the solution to send an image , audio or a video file with parameters using HttpURL
You can use Retrofit for API call. Minimum support for Android is 2.3. Please check details.
You can make it more simpler! Try the following.
public static String uploadImage(Bitmap bitmap, String urlString) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap = Local.resize(bitmap, 512, 512);
if(filename.toLowerCase().endsWith("jpg") || filename.toLowerCase().endsWith("jpeg"))
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos);
if(filename.toLowerCase().endsWith("png"))
bitmap.compress(Bitmap.CompressFormat.PNG, 70, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);
ContentBody body1 = new StringBody("something");
ContentBody body2 = new StringBody("something");
org.apache.http.entity.mime.MultipartEntity reqEntity = new org.apache.http.entity.mime.MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", contentPart);
reqEntity.addPart("sample1", body1);
reqEntity.addPart("sample2", body2);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(conn.getOutputStream());
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
Log.d("UPLOAD", "HTTP 200 OK.");
return readStream(conn.getInputStream());
//This return returns the response from the upload.
} else {
Log.d("UPLOAD", "HTTP "+conn.getResponseCode()+" "+conn.getResponseMessage()+".");
String stream = readStream(conn.getInputStream());
//Log.d("UPLOAD", "Response: "+stream);
return stream;
}
} catch (Exception e) {
Log.d("UPLOAD_ERROR", "Multipart POST Error: " + e + "(" + urlString + ")");
}
return null;
}