现在apache的MultipartEntityBuilder已被弃用,使用Volley库上传图像或文件的最佳方法是什么?

时间:2015-10-26 09:19:04

标签: android httprequest android-volley multipart

我过去常常使用Request对象的子组合使用MultipartEnityBuilderHttpEntity来上传图像和文件。现在它已被弃用,现在我已经迁移到Android Studio,我正在寻找一种更新的方式来执行上述任务,但是使用当前最好的方法来执行它,从API 15开始兼容。

我尝试过搜索,但Google仍会在此处返回引用MultipartEntityBuilderHttpEntity的指南和问题,所以我想我可以提问

2 个答案:

答案 0 :(得分:-1)

您是对的,MultipartEntity已被弃用,但您现在可以使用MultipartEntityBuilder。这是一个例子:

private void uploadVideo(String videoPath) {
    try
    {
        HttpClient client = new DefaultHttpClient();
        File file = new File(videoPath);
        HttpPost post = new HttpPost(server +"/api/docfile/");

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entityBuilder.addBinaryBody("uploadfile", file);
        // add more key/value pairs here as needed

        HttpEntity entity = entityBuilder.build();
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        HttpEntity httpEntity = response.getEntity();

        Log.v("result", EntityUtils.toString(httpEntity));
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

答案 1 :(得分:-1)

你可以在你的帖子中说清楚,如果是这样的情况是的,它在API 22中已被弃用,你现在可以使用URLconnection,这里是一个样本":

private StringBuffer request(String urlString) {
// TODO Auto-generated method stub

StringBuffer chaine = new StringBuffer("");
try{
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestProperty("User-Agent", "");
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.connect();

    InputStream inputStream = connection.getInputStream();

    BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    while ((line = rd.readLine()) != null) {
        chaine.append(line);
    }

} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

return chaine;

}