如何在Android 5.1中制作多部分HTTP POST请求?

时间:2015-11-04 04:14:31

标签: android http-post android-5.1.1-lollipop

自Android 5.1起,HttpPost和HttpMultipart类已被弃用。现在制作包含文件发送和邮件参数的POST请求的正确方法是什么?工作示例代码将受到高度赞赏。

另外,如果我们需要在libs文件夹中添加任何第三方库,请提及。

1 个答案:

答案 0 :(得分:0)

是的,Http客户端已被弃用,您可以使用HttpURLConnection。

示例:

private void uploadMultipartData() throws UnsupportedEncodingException
    {
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("fileToUpload", new FileBody(uploadFile));
        reqEntity.addPart("uname", new StringBody("MyUserName"));
        reqEntity.addPart("pwd", new StringBody("MyPassword"));
        String response = multipost(server_url, reqEntity);

        Log.e("", "Response :" + response);
    }


    private String multipost(String urlString, MultipartEntity reqEntity)
    {
        try
        {
            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)
            {
                return readStream(conn.getInputStream());
            }

        }
        catch (Exception e)
        {
            Log.e("MainActivity", "multipart post error " + e + "(" + urlString + ")");
        }
        return null;
    }

    private String readStream(InputStream in)
    {
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try
        {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }