Apache HttpClient库编写的Scala程序

Apache HttpClient库编写的Scala程序_第1张图片

Apache HttpClient库编写的Scala下载器程序,用于下载图片。代码如下:

import org.apache.http.HttpHost
import org.apache.http.client.HttpClients
import org.apache.http.client.methods.HttpHead
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients.createDefault
import org.apache.http.util.EntityUtils
​
object WeiboImageDownloader {
  def main(args: Array[String]): Unit = {
    val proxyHost = ""
    val proxyPort = 
    val host = new HttpHost(proxyHost, proxyPort, "http")
    val httpClient = HttpClients.createDefault()
    httpClient.getParams().setParameter("http.proxyHost", proxyHost)
    httpClient.getParams().setParameter("http.proxyPort", proxyPort.toString())
    val httpHead = new HttpHead("")
    val response = httpClient.execute(host, httpHead)
    val contentLength = response.getStatusLine().getStatusCode()
    if (contentLength == 200) {
      val entity = response.getEntity()
      if (entity != null) {
        val content = EntityUtils.toString(entity)
        println(content)
      }
    }
  }
}

程序首先导入所需的Apache HttpClient库和HttpHost,HttpClient和HttpHead类。然后,程序创建一个名为WeiboImageDownloader的类,并在其中定义一个名为main的方法。在main方法中,程序首先定义服务器的主机名和端口号,然后创建一个HttpClient对象,并设置其使用服务器。然后,程序创建一个HttpHead对象,并使用HttpClient对象执行该对象以获取网页的头部信息。然后,程序检查返回的状态码,如果状态码为200,则表示请求成功,程序获取响应实体,并将其内容打印到控制台。如果状态码不为200,则表示请求失败。

你可能感兴趣的:(apache,scala,大数据)