访问Java接口

如何通过java访问http接口

话不多说上代码,直接可用系列。

package src.main.scala.com.sf.spark.other

import com.alibaba.fastjson.{JSON, JSONObject}
import org.apache.http.HttpEntity
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.{HttpGet, HttpPost}
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.{CloseableHttpClient, HttpClientBuilder}
import org.apache.http.util.EntityUtils

import scala.util.control.Breaks.{break, breakable}

object MyHttpConn {
  val requestBuilder: RequestConfig.Builder = RequestConfig.custom()
  requestBuilder.setConnectionRequestTimeout(1500)
  requestBuilder.setConnectTimeout(1200)
  requestBuilder.setSocketTimeout(500)
  val builder: HttpClientBuilder = HttpClientBuilder.create()
  builder.setDefaultRequestConfig(requestBuilder.build())
  val httpClient: CloseableHttpClient = builder.build()

  def get(url: String): String = {
    val get = new HttpGet(url) // 创建 get 实例
    val response = httpClient.execute(get) // 发送请求
    val rs = EntityUtils.toString(response.getEntity) // 获取返回结果
    get.releaseConnection()
    rs
  }

  def post(url:String, json_str:String, retry:Int): String ={
    this.post(url,json_str = json_str,retry = retry,null,null)
  }

  def post(url: String, json_str: String,  retry: Int = 0, systemKey:String=null,accessKey:String=null): String = {
    assert(retry >= 0, "Http post retry num should gte zero!")
    val post = new HttpPost(url)
    post.addHeader("Content-Type", "application/json; charset=UTF-8")
    post.addHeader("Connection", "keep-alive")
    if(systemKey!=null)
      post.addHeader("systemKey",systemKey)
    if(accessKey != null)
      post.addHeader("accessKey",accessKey)
    val stringEntity = new StringEntity(json_str, "UTF-8")
    post.setEntity(stringEntity)
    var curRetry = 0
    var str = ""
    breakable {
      while (curRetry <= retry) {
        try {
          val response = httpClient.execute(post)
          val entity: HttpEntity = response.getEntity
          str = EntityUtils.toString(entity, "UTF-8")
          response.close()
          break()
        } catch {
          case e: Exception =>
            post.releaseConnection()
            if (curRetry == retry) {
              throw e
            }
            curRetry += 1
        }
      }
    }
    str
  }
  //example:请求pis接口获取承诺时效
  def queryPromiseExt(waybillNo: String, retryNum: Int = 1): JSONObject = {
    val timeStamp = System.currentTimeMillis()
    //调用接口参数
    val postJson = "{\"waybillNo\":\"%s\",\"systemCode\":\"%s\",\"queryTm\":\"%s\"}".format(waybillNo,"INC-AMDS-CORE",timeStamp)
    //替换成自己的接口地址
    val url = "http://public-int-gw-bdp-pis.int.sfdc.com.cn:1080/pis-data/WaybillRouteInfoService"
    var response: JSONObject = null
    try {
      response = JSON.parseObject(MyHttpConn.post(url, postJson, retryNum))
    } catch {
      case ex: Exception => println("queryPromiseExt fail : "+ ex.toString)
    }
    val data = if (response != null && "0"==response.getString("ret") && response.containsKey("data")) response.getJSONObject("data") else new JSONObject()
    //    println(response.toJSONString)
    val t4=System.currentTimeMillis()
    if (t4 % 50000 == 1) println("queryPromiseExt cost %sms.".format(t4 - timeStamp))
    data
  }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值