Java by setting Referer anti-hotlinking _jsp programming

Source: Internet
Author: User
Here is the complete code.
Copy Code code as follows:

Package cn.searchphoto.util;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.util.zip.GZIPInputStream;
/**
* Download pictures of remote Web site by setting referer anti-hotlinking.
*
* @author java Century Network (java2000.net, laozizhu.com)
*/
public class Imagedownloader {
/**
* Download files to the specified location
* @param imgurl Download Connection
* @param f Target Document
* @return successfully returned the file, failed to return null
*/
public static file Download (String Imgurl, file f) {
try {
URL url = new URL (imgurl);
URLConnection con = url.openconnection ();
int index = Imgurl.indexof ("/", 10);
Con.setrequestproperty ("Host", index = = 1 imgurl.substring (7): imgurl.substring (7, index));
Con.setrequestproperty ("Referer", Imgurl);
InputStream is = Con.getinputstream ();
if (con.getcontentencoding ()!= null && con.getcontentencoding (). Equalsignorecase ("gzip")) {
is = new Gzipinputstream (Con.getinputstream ());
}
Byte[] bs = new byte[1024];
int len =-1;
OutputStream OS = new FileOutputStream (f);
try {
while (len = Is.read (BS))!=-1) {
Os.write (BS, 0, Len);
}
finally {
try {
Os.close ();
catch (Exception ex) {}
try {
Is.close ();
catch (Exception ex) {}
}
return F;
catch (Exception ex) {
Ex.printstacktrace ();
return null;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.