import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class GetPic {
public static void getPicFromUrl(String url,String path)
{
int lastIndex=url.lastIndexOf("/")+1;
String fileName = url.substring(lastIndex);
System.setProperty("User-Agent", "");
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,"Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");//设置信息
httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
httpClient.getParams().setSoTimeout(30 * 1000);
//httpClient.setTimeout(30000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(30 * 1000);
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
GetMethod getMethod=null;
try {
getMethod = new GetMethod(url);
//设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println(" Method failed: "
+ getMethod.getStatusLine());
}
//byte[] responseBody = getMethod.getResponseBody();
InputStream in=getMethod.getResponseBodyAsStream();
writeImageToDisk(InputStreamToByte(in), fileName,path);
//writeImageToDisk(responseBody, fileName,j);
} catch (Exception e) {
System.out.println(" Please check your provided http address! ");
e.printStackTrace();
} finally {
if(getMethod!=null)
{
getMethod.releaseConnection();
}
}
}
private static byte[] InputStreamToByte(InputStream is) {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
byte[] imgdata = null;
try {
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
imgdata = bytestream.toByteArray();
bytestream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imgdata;
}
public static void main(String[] args) {
}
/**
* 将图片写入到磁盘
* @param img 图片数据流
* @param fileName 文件保存时的名称
*/
public static void writeImageToDisk(byte[] img, String fileName,String path){
try {
//File file = new File("F:\\pic\\" +j+"\\"+ fileName);
File file = new File(path+"\\"+ fileName);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
System.out.println("已经下载完成:"+file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}