想抓取某些网站经过servlet生成的图片,简单的就是经过HttpClient来实现: java
String url = "http://xxxx/pictureservlet?size=100"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = httpclient.execute(httpGet); try { System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity.isStreaming()) { String destinationFile = "d://tmp//image.jpg"; OutputStream os = new FileOutputStream(destinationFile); entity.writeTo(os); } } finally { httpGet.releaseConnection(); }固然上面的代码也能够直接使用scala来写,更方便。另外使用Htmlunit也许更简单,这个是模仿浏览器的行为。
若是使用sbt增长 web
"org.seleniumhq.selenium" % "selenium-java" % "2.35.0" 就能够使用了。 浏览器
val webClient = new WebClient val page: UnexpectedPage = webClient.getPage("http://xxx/pictureservlet?size=100") val input = page.getWebResponse().getContentAsStream() val destinationFile = "d://tmp//image.jpg" val os = new FileOutputStream(destinationFile) os.write(IOUtils.toByteArray(input)) os.close() input.close()为何下载图片要单独写这文章,由于以前下载的图片的网站必需要求从首页进入,可能增长了session或相关的标识来记录下载图片是否是从首页来进入,若是模仿cookie或session比较麻烦的时候,这时使用selenium来模拟浏览器操做也许是最方便的。
上面的HttpClient对这种状况也是可行的,直接发送一次首页请求,这个链接是共享的,那么进行下载图片是就认为是有效的请求了。 cookie