引子
最近公司需要请求数据接口去获取数据,用到了get请求和post请求,总结一下
get请求:
get请求参数是携带在url里面的,在?后面携带参数,每个参数之间用&隔开,举例:
www.baidu?name=lisan&age=18
如果参数里面有中文要把中文转成unicode编码,代码很简单:
val client = new HttpClient
// 设置代理服务器地址和端口
val city = URLEncoder.encode("北京")
//把中文转成Unicode编码
// 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https
val method = new GetMethod("url")
client.executeMethod(method)
//打印服务器返回的状态
println(method.getStatusLine)
//打印返回的信息
println(method.getResponseBodyAsString)
//释放连接
method.releaseConnection()
post请求
post请求携带参数可以比较多,不在url里面,是要set进去的。下面附上两种方式,一种是把参数都转成json格式set进去,一种是直接set就去,代码如下:
1.直接set
val httpClient = Utils.getHttpClient
try { //url
val post = new HttpPost("url")
//创建参数列表
val list = new util.ArrayList[NameValuePair]
list.add(new BasicNameValuePair("timestamp", time))
list.add(new BasicNameValuePair("signature", signature))
list.add(new BasicNameValuePair("ID", "1"))
//提交参数
val uefEntity = new UrlEncodedFormEntity(list, "UTF-8")
post.setEntity(uefEntity)
//执行请求
val httpResponse = httpClient.execute(post)
try {
//获取返回结果
val entity: HttpEntity = httpResponse.getEntity
val str = EntityUtils.toString(entity, "UTF-8")
//业务逻辑
if (null != str) {
prinln(str)
}
} finally httpResponse.close()
} catch {
case e: UnsupportedEncodingException =>
e.printStackTrace()
case e: IOException =>
e.printStackTrace()
} finally try
Utils.closeHttpClient(httpClient)
catch {
case e: Exception =>
e.printStackTrace()
}
2.把参数转成json格式
//把参数转换成json格式
val jsonObj = new JSONObject
jsonObj.put("name",lisi)
jsonObj.put("age",18)
val url = "url"
val client = HttpClients.createDefault()
val post: HttpPost = new HttpPost(url)
//设置提交参数为application/json
post.addHeader("Content-Type", "application/json")
post.setEntity(new StringEntity(jsonObj.toJSONString))
//执行请求
val response: CloseableHttpResponse = client.execute(post)
//返回结果
val allHeaders: Array[Header] = post.getAllHeaders
val entity: HttpEntity = response.getEntity
val string = EntityUtils.toString(entity, "UTF-8")