手机客户端从服务器上下载文件(post方法)

手机客户端从服务器上下载文件(post方法)
1.建立连接   
     HttpClient httpclient = new DefaultHttpClient();
2.创建存放路径
   Environment.getExternalStorageDirectory();
    String saveDir =sdCardDir.getCanonicalPath() +"/DownFile";
    
    File file1 = new File(saveDir);
    if(!file1.exists()){
     file1.mkdir();
    }
3.选择传值方法(post或者get)
    HttpPost httpRequest = new HttpPost(url);
    HttpResponse response = httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream is = bufHttpEntity.getContent();
    FileOutputStream out = new FileOutputStream(saveDir,false);
    bufferedOutputStream = new BufferedOutputStream(
      out);
    bufferedInputStream = new BufferedInputStream(
      is);
    byte[] buf = new byte[4096];
    
    int bytesRead = 0;
    while (bytesRead >= 0) {
     long now = System.currentTimeMillis();
     bufferedOutputStream.write(buf, 0, bytesRead);
     bytesRead = bufferedInputStream.read(buf);
    }
    bufferedOutputStream.flush();

4.关闭流及httpclient
    bufferedOutputStream.close();
     out.close();
     if(bufferedOutputStream!=null){
      bufferedOutputStream.close();
     }
     if(out!=null){
      out.close();
     }
     if(bufferedInputStream!=null){
      bufferedInputStream.close();
     }
     if(is!=null){
      is.close();
     }
     shutdownHttpClient();

    private void shutdownHttpClient() {
        if (httpclient != null && httpclient.getConnectionManager() != null) {
         httpclient.getConnectionManager().shutdown();
        }
 }
    

你可能感兴趣的:(手机客户端从服务器上下载文件(post方法))