2015-11-04 100 views
0

从Android 5.1开始,HttpPost和HttpMultipart类已被弃用。现在有什么正确的方法来使POST请求包括文件发送和后参数?工作示例代码将受到高度赞赏。如何在Android 5.1中创建多部分HTTP POST请求?

此外,请提及是否需要在libs文件夹中添加任何第三方库。

回答

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(); 
    }  
+0

但MultipartEntity还弃用。 – Adnan

+0

使用MultiPartEntityBuilder与HttpURLConnection –

+0

用MultiPartEntityBuilder替换MultipartEntity,但它会生成像reqEntity.getContentLength()函数未找到等错误。 – Adnan