HttpURLConnection to Send image , audio and video files with parameter may (String or Json String) Android

送分小仙女□ 提交于 2019-11-27 11:07:26

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!