import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.log.exception.BizServiceException;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
/**
* HTTP工具箱
* <p/>
* Created by gryang on 15-04-15.
*/
public final class HttpTookit {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpTookit.class);
/**
* get请求
*
* @return
*/
public static String doGet(String url) {
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* get请求,header请求头可接受参数
*
* @return
*/
public static String doGet(String url, String token) {
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
request.setHeader("authorization", token);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param params 请求的查询参数,可以为null
* @return 返回请求响应的数据
*/
public static String doPost(String url, Map<String, String> params) {
LOGGER.info("请求的地址为:{},请求的参数为:{}",url,params);
List<NameValuePair> list = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = String.valueOf(entry.getValue());
list.add(new BasicNameValuePair(entry.getKey(), value));
}
String result = null;
try {
HttpResponse response = Request.Post(url).connectTimeout(60000).socketTimeout(60000)
.bodyForm(list).execute().returnResponse();
result = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
LOGGER.error("执行HTTP Post请求" + url + "时,发生异常!", e);
e.printStackTrace();
}
LOGGER.info("返回的结果为:{}",result);
return result;
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @return 返回请求响应的数据
*/
public static String doPost(String url) {
try {
HttpResponse response = Request.Post(url).connectTimeout(60000).socketTimeout(60000)
.execute().returnResponse();
return EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
LOGGER.error("执行HTTP Post请求" + url + "时,发生异常!", e);
e.printStackTrace();
}
return null;
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @return 返回请求响应的数据
*/
public static String doPostForJson(String url, String json) {
try {
BasicNameValuePair nameValuePair = new BasicNameValuePair("Authorization",
"Basic " + "c9e1be2768b238d835679f6ab1d97a");
LOGGER.info("执行HTTP Post请求" + url + ",请求的json为:" + json);
HttpResponse response = Request.Post(url).bodyForm(nameValuePair)
.bodyString(json, ContentType.APPLICATION_JSON).connectTimeout(60000)
.socketTimeout(60000).execute().returnResponse();
return EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
LOGGER.error("执行HTTP Post请求" + url + "时,发生异常!", e);
e.printStackTrace();
}
return null;
}
/**
* POST 请求 返送json数据
* @param URL 地址
* @param json json字符串
* @return
*/
public static ByteArrayInputStream sendPost(String URL, String json) {
InputStream inputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(URL);
httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
try {
StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
s.setContentEncoding("UTF-8");
httppost.setEntity(s);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 获取相应实体
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inputStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inputStream.close();
// 把outStream里的数据写入内存
byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return byteArrayInputStream;
}
/**
* POST请求 带请求头和请求参数
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头
* @return
*/
public static String doPostWithHeader(String url, Map<String, Object> params, Map<String, String> headers) {
LOGGER.info("请求的地址为:{},请求的参数为:{}", url, params);
List<NameValuePair> list = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = String.valueOf(entry.getValue());
list.add(new BasicNameValuePair(entry.getKey(), value));
}
String result = null;
try {
Request request = Request.Post(url);
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
HttpResponse response = request.connectTimeout(60000).socketTimeout(60000)
.bodyForm(list, Charset.forName("UTF-8")).execute().returnResponse();
result = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
LOGGER.error("执行HTTP Post请求" + url + "时,发生异常!", e);
e.printStackTrace();
}
LOGGER.info("返回的结果为:{}", result);
return result;
}
/**
* 发送xml数据,获取返回结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式
* @param xmlStr 请求的xml报文
* @return
*/
public static String httpXmlRequest(String requestUrl, String requestMethod, String xmlStr) {
// 将解析结果存储在HashMap中
Map<String, Object> map = new HashMap<String, Object>();
BufferedReader br = null;
try {
HttpsURLConnection urlCon = (HttpsURLConnection) (new URL(requestUrl)).openConnection();
urlCon.setDoInput(true);
urlCon.setDoOutput(true);
// 设置请求方式(GET/POST)
urlCon.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod)) {
urlCon.connect();
}
urlCon.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length));
urlCon.setUseCaches(false);
// 设置为gbk可以解决服务器接收时读取的数据中文乱码问题
if (null != xmlStr) {
OutputStream outputStream = urlCon.getOutputStream();
outputStream.write(xmlStr.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
}
br = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
for (line = br.readLine(); line != null; line = br.readLine()) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
LOGGER.error(e.getMessage());
} finally {
try {
br.close();
} catch (IOException e) {
LOGGER.error("关闭流异常",e);
}
}
return null;
}
}
|