HTTP 请求
Get Request
import java.net.URLEncoder
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
def get(url: String, headers: Map[String, String], data: Map[String, String]): String = {
val httpClient = HttpClients.createDefault()
var dataArray: Array[String] = Array()
for ((k, v) <- data) {
val encodeValue = URLEncoder.encode(v, "utf-8")
dataArray :+= s"$k=$encodeValue"
}
val dataStr = dataArray.mkString("&")
val request = new HttpGet(s"$appUrl?$dataStr")
for ((k, v) <- headers) request.addHeader(k, v)
val response = httpClient.execute(request)
val handler = new org.apache.http.impl.client.BasicResponseHandler()
val result = handler.handleResponse(response).trim
httpClient.close()
result
}
Post Request
import org.apache.http.NameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
def post(url: String, headers: Map[String, String], data: Map[String, String]): String = {
val httpClient = HttpClients.createDefault()
val request = new HttpPost(url)
for ((k, v) <- headers) request.addHeader(k, v)
val nameValuePairs = new java.util.ArrayList[NameValuePair]()
for ((k, v) <- data) nameValuePairs.add(new BasicNameValuePair(k, v))
request.setEntity(new UrlEncodedFormEntity(nameValuePairs))
val response = httpClient.execute(request)
val handler = new org.apache.http.impl.client.BasicResponseHandler()
val result = handler.handleResponse(response).trim
httpClient.close()
result
}