import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
@Service
public class HttpService {
// 创建HttpClient对象
@Autowired(required = false)
private CloseableHttpClient httpClient;
/* @Autowired(required = false)表示的含义是,spring容器里面有这个bean就注入,没有就不注入。 */
// 请求信息的配置
@Autowired(required = false)
private RequestConfig requestConfig;
/**
* 执行Get请求
*
* @param url
* @return 请求到的内容
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public String doGet(String url) throws URISyntaxException, ClientProtocolException, IOException {
return doGet(url, null);
}
/**
* @param url
* @param intoParams 请求中的参数
* @return 请求到的内容
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws IOException
*/
public String doPost(String url) throws URISyntaxException, ClientProtocolException, IOException {
return doPost(url, null);
}
/**
* 执行Get请求
*
* @param url
* @param params 请求中的参数
* @return 请求到的内容
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public String doGet(String url, Map<String, Object> params) throws URISyntaxException, ClientProtocolException, IOException {
// 定义请求的参数
URI uri = null;
if (params != null) {
URIBuilder builder = new URIBuilder(url);
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
}
uri = builder.build();
}
// 创建http GET请求
HttpGet httpGet = null;
if (uri != null) {
httpGet = new HttpGet(uri);
} else {
httpGet = new HttpGet(url);
}
// 设置请求参数
httpGet.setConfig(this.requestConfig);
// 请求的结果
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 获取服务端返回的数据,并返回
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* @param url
* @param params 请求中的参数
* @return 请求到的内容
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws IOException
*/
public String doPost(String url, Map<String, Object> params)
throws URISyntaxException, ClientProtocolException, IOException {
// url = GlobalUtil.getValue("remoteAddress") + url;
// 设置post参数
List<NameValuePair> parameters = null;
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = null;
// 定义请求的参数
if (params != null) {
// 设置post参数
parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
// 添加参数
parameters.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
// 构造一个form表单式的实体
formEntity = new UrlEncodedFormEntity(parameters);
}
// 创建HTTP GET请求
HttpPost httpPost = null;
if (formEntity != null) {
httpPost = new HttpPost(url);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
// 伪装浏览器请求
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
} else {
httpPost = new HttpPost(url);
// 伪装浏览器请求
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
}
// 设置请求参数
httpPost.setConfig(this.requestConfig);
// 请求的结果
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 获取服务端返回的数据,并返回
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**使用post以“raw-JSON(application/json)”类型推送数据
* @param url
* @param params 请求中的参数
* @return 请求到的内容
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws IOException
*/
public String httpPostWithJSON(String url, Map<String, Object> params) throws URISyntaxException, ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
// 设置post参数
StringEntity entity = null;
// 构造一个form表单式的实体
// 定义请求的参数
if (params != null) {
// 设置post参数
String json = JSON.toJSONString(params);// map转String
JSONObject jsonObject = JSON.parseObject(json);// String转json
entity = new StringEntity(jsonObject.toString(), "utf-8");// 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
}
// 创建HTTP GET请求
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
try {
// 执行请求
HttpResponse response = client.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 获取服务端返回的数据,并返回
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (client != null) {
client.close();
}
}
return null;
}
/**
* 使用post以“x-www-form-urlencoded”类型推送数据
*
* @param url
* @param params 请求中的参数
* @return 请求到的内容
*/
public String httpSendPost(String url, Map<String, Object> params) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Map.Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
URLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
if (sbParams != null && sbParams.length() > 0) {
// 发送请求参数
osw.write(sbParams.substring(0, sbParams.length() - 1));
// flush输出流的缓冲
osw.flush();
}
// 定义BufferedReader输入流来读取URL的响应
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
}
}