如何通过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
}
}