• 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()
        }
      }
    }
    
    
  • 相关阅读:
    Redis 哨兵机制以及灾难演练
    经典的Redis的主从复制搭建
    Redis的几个核心机制底层原理
    Redis Sentinel(哨兵核心机制) 初步深入
    从零开始装CentOS以及配置Redis,前端都可以!!!
    在项目中部署redis的读写分离架构(包含节点间认证口令)
    读懂MySQL执行计划
    SpringBoot之自动配置原理
    排序算法总结
    拉格朗日插值法理论与编程实现
  • 原文地址:https://www.cnblogs.com/aixing/p/13327272.html
Copyright © 2020-2023  润新知