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 {
val httpget = new HttpGet(url)
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 = {
val client = HttpClients.createDefault
try {
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) {
body = EntityUtils.toString(entity, "UTF-8")
}
response.close()
body
} finally {
client.close()
}
}
}