java download image from url with basic authentication

String username = "userId"
String password = "******"
String imagePath = "C:\\Users\\MyUser\\Downloads\\";
String filename = imagePath + "myImageName.jpg";
String url = "http://www.mysamplecode.com/images/logo.jpg";

boolean success = downloadImage(url , username, password, filename);


 private boolean downloadImage(String url, String username, String password,
   String fileName) {

  boolean success = true;
  InputStream in = null;
  FileOutputStream out = null;

  try{ 

   URL myUrl = new URL(url);
   HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
   conn.setDoOutput(true);
   conn.setReadTimeout(30000);
   conn.setConnectTimeout(30000);
   conn.setUseCaches(false);
   conn.setAllowUserInteraction(false);
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setRequestProperty("Accept-Charset", "UTF-8");
   conn.setRequestMethod("GET");

   String userCredentials = username.trim() + ":" + password.trim();
   String basicAuth = "Basic " + new String(Base64.encodeBytes(userCredentials.getBytes()));
   conn.setRequestProperty ("Authorization", basicAuth);

   in = conn.getInputStream();
   out = new FileOutputStream(fileName);
   int c;
   byte[] b = new byte[1024];
   while ((c = in.read(b)) != -1)
    out.write(b, 0, c);

  } 

  catch (Exception ex) {
   logger.error(ex,ex);
   success = false;
  } 

  finally {
   if (in != null)
    try {
     in.close();
    } catch (IOException e) {
     logger.error(e,e);
    }
   if (out != null)
    try {
     out.close();
    } catch (IOException e) {
     logger.error(e,e);
    }
  }

  return success;

 }

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.