zoukankan      html  css  js  c++  java
  • HttpClientUtils:Http请求工具类

    HttpClientUtils:Http请求工具类

    Scala:HttpClientUtils

    import java.io.IOException
    import java.util
    import org.apache.http.client.ClientProtocolException
    import org.apache.http.client.entity.UrlEncodedFormEntity
    import org.apache.http.client.methods.{HttpGet, HttpPost}
    import org.apache.http.impl.client.{DefaultHttpClient, HttpClients}
    import org.apache.http.message.BasicNameValuePair
    import org.apache.http.util.EntityUtils
    import org.slf4j.LoggerFactory
    import scala.collection.JavaConversions._
    import scala.reflect.macros.ParseException
    
    object HttpClientUtils {
    
      val logger = LoggerFactory.getLogger("out")
    
      def get(url: String): String = {
        val httpclient = new DefaultHttpClient()
        try {
          // 创建httpget.
          val httpget = new HttpGet(url)
          // 执行get请求.
          val response = httpclient.execute(httpget)
          try {
            // 获取响应实体
            val entity = response.getEntity()
            EntityUtils.toString(entity, "utf-8")
          } finally {
            response.close()
          }
        } catch {
            case ex: ClientProtocolException => {logger.error(ex.getMessage);null}
            case ex: ParseException => {logger.error(ex.getMessage);null}
            case ex: IOException => {logger.error(ex.getMessage);null}
        } finally {
          // 关闭连接,释放资源
          httpclient.close()
        }
    
      }
    
      def post(url: String, map: Map[String,String]): String = {
        //创建httpclient对象
        val client = HttpClients.createDefault
        try {
          //创建post方式请求对象
          val httpPost = new HttpPost(url)
          //装填参数
          val nvps:util.ArrayList[BasicNameValuePair] = new util.ArrayList[BasicNameValuePair]
          if (map != null) {
            for (entry <- map.entrySet) {
              nvps.add(new BasicNameValuePair(entry.getKey, entry.getValue))
            }
          }
          //设置参数到请求对象中
          httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"))
          //执行请求操作,并拿到结果(同步阻塞)
          val response = client.execute(httpPost)
          //获取结果实体
          val entity = response.getEntity
          var body = ""
          if (entity != null) { //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "UTF-8")
          }
          //释放链接
          response.close()
          body
        } finally {
           client.close()
        }
      }
    }
    
    
  • 相关阅读:
    python3.x元组打印错误 TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
    LoRa---她的简介和她的专业术语
    单片机程序在内存和FLASH中的空间分配
    STM32烧录的常用方式
    【原创】MapReduce编程系列之表连接
    Maven基础配置—本地Maven配置
    Maven基础配置--nexus私服配置
    OSGI入门笔记
    Maven仓库搭建--nexus私服
    javascript基础 方法 函数 闭包 集合
  • 原文地址:https://www.cnblogs.com/aixing/p/13327272.html
Copyright © 2011-2022 走看看