title: Download a file from Google Drive By Url In Android
body: <p>I am developing an app to uploading ,displaying and downloading files from G Drive. Unfortunately When downloading I am getting<br>
   <strong>com.google.api.client.http.HttpResponseException: 401 Unauthorized.</strong></p>
  
  <p>Please help me to solve this problem.</p>
  
  <p>Here I am assigning</p>
  
  <pre><code>credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
  
  service=new Drive.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(),credential).build();
  </code></pre>
  
  <p>My Code Is:   </p>
  
  <pre><code>package com.example.googledrive;
  
  import java.io.BufferedOutputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.HttpURLConnection;
  import java.net.URL;
  import java.net.URLConnection;
  import java.nio.channels.Channels;
  import java.nio.channels.ReadableByteChannel;
  import java.text.SimpleDateFormat;
  import java.util.ArrayList;
  import java.util.Date;
  import java.util.List;
  import java.util.Locale;
  
  import com.google.api.client.extensions.android.http.AndroidHttp;
  import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
  import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
  import com.google.api.client.http.FileContent;
  import com.google.api.client.http.GenericUrl;
  import com.google.api.client.http.HttpResponse;
  import com.google.api.client.json.gson.GsonFactory;
  import com.google.api.services.drive.Drive;
  import com.google.api.services.drive.Drive.Children;
  import com.google.api.services.drive.Drive.Files;
  import com.google.api.services.drive.Drive.Files.Get;
  import com.google.api.services.drive.DriveScopes;
  import com.google.api.services.drive.model.ChildList;
  import com.google.api.services.drive.model.ChildReference;
  import com.google.api.services.drive.model.File;
  import com.google.api.services.drive.model.FileList;
  
  import android.net.Uri;
  import android.os.Bundle;
  import android.os.Environment;
  import android.os.StrictMode;
  import android.provider.MediaStore;
  import android.accounts.AccountManager;
  import android.app.Activity;
  import android.app.ProgressDialog;
  import android.content.Intent;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
  import android.widget.ListView;
  import android.widget.Toast;
  
  public class MainActivity extends Activity {
  
      static final int REQUEST_ACCOUNT_PICKER = 1;
      static final int REQUEST_AUTHORIZATION = 2;
      static final int CAPTURE_IMAGE = 3;
  
      private static Uri fileUri;
      private static Drive service;
      private ProgressDialog progressDialog;
      private GoogleAccountCredential credential;
  
      String fileId;
      String fileName;
      String downloadUrl;
      ListView listView;
      Activity activity;
      String sdCardPadth;
      List&lt;File&gt; allFileList;
      ArrayList&lt;String&gt; fileType;
      ArrayList&lt;String&gt; mainTitleList;
      ArrayList&lt;String&gt; fileIdList;
      ArrayList&lt;String&gt; alternateUrlList;
      ArrayList&lt;Integer&gt; fileSizeList;
      FileTitlesAdapter myAdapter;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          listView = (ListView) findViewById(R.id.uploadedFilesList);
          allFileList = new ArrayList&lt;File&gt;();
          mainTitleList = new ArrayList&lt;String&gt;();
          alternateUrlList = new ArrayList&lt;String&gt;();
          fileSizeList = new ArrayList&lt;Integer&gt;();
          fileType = new ArrayList&lt;String&gt;();
          fileIdList=new ArrayList&lt;String&gt;();
          progressDialog=new ProgressDialog(getApplicationContext());
          progressDialog.setTitle("Please Wait....");
          progressDialog.setCancelable(false);
          activity = this;
  
          credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
          startActivityForResult(credential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
          listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              public void onItemClick(AdapterView&lt;?&gt; arg0, View view, final int arg2,long arg3) {
                  // String str=itemArray.get(arg2).toString().trim();
                  System.out.println("mainTitleList size==="+mainTitleList.size());
                  System.out.println("arg2==="+arg2);
                  fileName = (String)mainTitleList.get(arg2);             
                  mainTitleList.clear();              
                  //fileSizeList.clear();
                  final String fileTypeStr=fileType.get(arg2);
                  fileType.clear();
                  if(fileTypeStr.contains("application/vnd.google-apps.folder"))
                  {
                      Thread t = new Thread(new Runnable() {
                          @Override
                          public void run() {
                      boolean b=true;
                      try {                       
                          String dirUrl=alternateUrlList.get(arg2);                       
                          alternateUrlList.clear();
                          System.out.println("Folder Name Is:"+fileName);
                          System.out.println("Folder Type Is:"+fileTypeStr);
                          System.out.println("Folder URL Is:"+dirUrl);
                          String fileId=fileIdList.get(arg2);
                          System.out.println("Folder Id Is:"+fileId);                     
                          //retrieveAllFilesFromDir(service, fileId, b);                      
                          //retrieveAllFiles1(service, b, fileId);
                          //Files.List request = service.children().get(fileId, null);
                          Files.List request = service.files().list().setQ("'" + fileId + "' in parents ");
                          retrieveAllFiles(service,request,b);                        
                          //retrieveAllFiles(service, b);
                      } catch (Exception e) {
                          // TODO Auto-generated catch block
                          System.out.println("Exception In retrieveAllFiles Dir Is:"+e);
                          e.printStackTrace();
                      }
                          }
                          });t.start();       
                  }
                  else
                  {       
  
                  try {
                      System.out.println("fileSizeList size===="+fileSizeList.size());
                      System.out.println("arg2===="+arg2);                    
                      Integer fileSize = (int) fileSizeList.get(arg2);
                      downloadUrl = alternateUrlList.get(arg2);
                      byte[] size = new byte[fileSize];
                      int byteRead = 0, byteWritten = 0;
                      sdCardPadth = Environment.getExternalStorageDirectory().getPath();
  
  
                      System.out.println("Download Url==="+downloadUrl);
  
                      new Thread(new Runnable() {
  
                          @Override
                          public void run() {
                              // TODO Auto-generated method stub
                              InputStream inStream=downloadFile(service, downloadUrl);
  
                              java.io.File inFile=new java.io.File(sdCardPadth+"/"+fileName+"1");
                              System.out.println("File Succesfully Stored");
  
                          }
                      }).start();
                  } catch (Exception e) {
                      // TODO Auto-generated catch block
                      System.out.println("Exception In get Integer Is:" + e);
                      e.printStackTrace();
                  }
                  }
              }
          });
      }
  
      @Override
      protected void onActivityResult(final int requestCode,
              final int resultCode, final Intent data) {      
          switch (requestCode) {
          case REQUEST_ACCOUNT_PICKER:            
              if (resultCode == RESULT_OK &amp;&amp; data != null
                      &amp;&amp; data.getExtras() != null) {
                  String accountName = data
                          .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                  if (accountName != null) {
                      credential.setSelectedAccountName(accountName);
                      service = getDriveService(credential);      
                      final boolean b=false;                  
                      Thread t=new Thread(new Runnable() {                        
                          @Override
                          public void run() {
                              try
                              {
                                  Files.List request = service.files().list().setQ("hidden="+b);
                                      retrieveAllFiles(service,request,b);
                              } catch (Exception e) {
                                  System.out.println("Exception Is:"+e);
                                  e.printStackTrace();
                              }
  
                          }
                      }) ;t.start();
  
                  }
              }
              break;
          case REQUEST_AUTHORIZATION:
              if (resultCode == Activity.RESULT_OK) {
                  System.out.println("REQUEST_AUTHORIZATION case Is:"
                          + REQUEST_AUTHORIZATION);
                  saveFileToDrive();
              } else {
                  startActivityForResult(credential.newChooseAccountIntent(),
                          REQUEST_ACCOUNT_PICKER);
              }
              break;
          case CAPTURE_IMAGE:
              if (resultCode == Activity.RESULT_OK) {
                  System.out.println("CAPTURE_IMAGE case Is:" + CAPTURE_IMAGE);
                  saveFileToDrive();
              }
          }
      }
      private void saveFileToDrive() {
          Thread t = new Thread(new Runnable() {
              @Override
              public void run() {
                  try {
                      // File's binary content
                      System.out.println("run method");
                      java.io.File fileContent = new java.io.File(fileUri.getPath());
                      FileContent mediaContent = new FileContent("image/jpeg",fileContent);
                      // File's metadata.
                      File body = new File();
                      body.setTitle(fileContent.getName());
                      body.setMimeType("image/jpeg");
                      File file=null;
                      try {
  
                          file = service.files().insert(body, mediaContent).execute();
                      } catch (Exception e) {
  
                          System.out.println("Exception In Insert File Is"+e);
                          e.printStackTrace();
                      }
                      if (file != null) {
                          showToast("Photo uploaded: " + file.getTitle());
                          System.out.println("photo sucessfullly uploaded:"+ fileId);boolean b=false;
  Files.List request = service.files().list().setQ("hidden="+b);
                          retrieveAllFiles(service,request,b);                        
                      }
                  } catch (UserRecoverableAuthIOException e) {
                      startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          });
          t.start();
      }
      private Drive getDriveService(GoogleAccountCredential credential) {
          return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
                  new GsonFactory(), credential).build();
      }
  
      public void showToast(final String toast) {
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  Toast.makeText(getApplicationContext(), toast,Toast.LENGTH_SHORT).show();
              }
          });
      }
  
      private List&lt;File&gt; retrieveAllFiles(Drive service,Files.List request,boolean b) throws IOException {
          List&lt;File&gt; result = new ArrayList&lt;File&gt;();
          final ArrayList&lt;String&gt; titleList = new ArrayList&lt;String&gt;();
          String fileUrl = "";
          do {
              try {
                  FileList files = request.execute();
                  result.addAll(files.getItems());
                  request.setPageToken(files.getNextPageToken());
                  for (int i = 0; i &lt; result.size(); i++) {
                      File tempFile = result.get(i);
                      String fileTypeStr = tempFile.getMimeType();                
                      String fileName = tempFile.getTitle();
                      titleList.add(fileName);    
                      fileId = tempFile.getId();
                      fileIdList.add(fileId);                 
                      fileUrl = tempFile.getAlternateLink();
                      System.out.println("&lt;&gt;&lt;&gt;&lt; fileUrl Is:" + fileUrl);
                      alternateUrlList.add(fileUrl);
  
                      fileType.add(fileTypeStr);
                      mainTitleList.add(fileName);                    
  
                      try {
                          Integer fileSize =tempFile.getFileSize()==null?100:(int) (long) tempFile.getFileSize();
                          fileSizeList.add(fileSize);
                          System.out.println("&lt;&gt;&lt;&gt;&lt; fileSize Is:" + fileSize);
                      } catch (Exception e) {
  
                          fileSizeList.add(2000);
                          e.printStackTrace();
                      }
  
  
                  }
  
  
  
                  try {
                      runOnUiThread(new Runnable() {
                          public void run() {
  
                              myAdapter = new FileTitlesAdapter(activity,
                                      fileType, mainTitleList, alternateUrlList,
                                      fileSizeList);
                              listView.setAdapter(myAdapter);
                          }
                      });
  
                  } catch (Exception e) {
  
  
                      System.out.println("Exception Setting ListView Is:" + e);
                      e.printStackTrace();
                  }
              } catch (IOException e) {
                  System.out.println("An error occurred in retrieveAllFiles:"+ e);
                  request.setPageToken(null);
              }
          } while (request.getPageToken() != null
                  &amp;&amp; request.getPageToken().length() &gt; 0);
          return result;
      }
  
  
       private static InputStream downloadFile(Drive service, String url) {
           System.out.println("downloadFile is called service=="+service);
              if (url != null &amp;&amp; url.length() &gt; 0) {
                try {
                    System.out.println("downloadFile is called try");
                  HttpResponse resp =service.getRequestFactory().buildGetRequest(new GenericUrl(url)).execute();
                  System.out.println("resp.getContent()===="+resp.getContent());
                  return resp.getContent();
                } catch (Exception e) {
                  System.out.println("Exception Is:"+e);
                  e.printStackTrace();
                  return null;
                }
              } else {
                   System.out.println("No Exception No Output");
                return null;
              }
            }
  
  
  }
  </code></pre>