2015-11-04 118 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