天天看點

通過 URL類擷取帶密碼驗證資源檔案的處理方法

package com.test;

import java.io.bufferedoutputstream;

import java.io.file;

import java.io.fileoutputstream;

import java.io.ioexception;

import java.io.inputstream;

import java.io.outputstream;

import java.net.malformedurlexception;

import java.net.url;

import java.net.urlconnection;

import java.util.date;

public class test{

 /**

  * @param args

  */

 public static void main(string[] args) {

  string imageurl="http://www.baidu.com/img/logo-yy.gif";

  url url;

  string theusername="test";

  string thepassword="test";

  try {

   url = new url (imageurl);

   string userpassword = theusername + ":" + thepassword;

   string encoding = new sun.misc.base64encoder().encode (userpassword.getbytes());

   //實際上url的openconnection的傳回值就是一個urlconnection

      urlconnection c;

   try {

    c = url.openconnection();

    c.setrequestproperty ("authorization", "basic " + encoding);

       //用urlconnection的connect()方法建立連接配接

       c.connect();                            //*

       // 顯示該連接配接的相關資訊,這些都是urlconnection的方法

       system.out.println("内容類型: "+c.getcontenttype());

       system.out.println("内容長度: "+c.getcontentlength());

       system.out.println("建立日期: "+new date(c.getdate()));

       system.out.println("最後修改日期: "+new date(c.getlastmodified()));

       system.out.println("終止日期: "+new date(c.getexpiration()));

       inputstream in=c.getinputstream();

    string pathname = savetempfile(in,"test.jpg");

    system.out.println(pathname);

   } catch (ioexception e) {

    // todo auto-generated catch block

    e.printstacktrace();

   } //*

  } catch (malformedurlexception e) {

   // todo auto-generated catch block

   e.printstacktrace();

  }

 }

 private static string savetempfile(inputstream inputstream,string fllename) {

  string pathname = gettempfilename(fllename);  

  file tmpfile = new file(pathname);

  outputstream out = null;

   out = new bufferedoutputstream(new fileoutputstream(tmpfile));

   int length = 1024 * 1024;

   byte[] buffer = new byte[length];

   while ((length = inputstream.read(buffer)) > 0) {

    out.write(buffer, 0, length);

   }

  } catch (exception e) {

   //global.logger.error("save temp file exception!");

  } finally {

   resourcemgr.closequietly(out);

  return pathname;

 private static string gettempfilename(string filename) {

  //return system.getproperty("user.dir")+ file.separator+system.currenttimemillis() + ".gif";

  return system.getproperty("user.dir")+ file.separator + filename;

}

注意 關鍵:

繼續閱讀