http工具类
·
package com.hn.whistle.daHua;
import com.alibaba.nacos.common.codec.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class HttpClientUtils {
/**
* 发送get请求
*
* @param url 请求地址
* @return
*/
public static String doGet(String url) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 发送POST请求,携带map格式的参数
* 如:name="jok",age="10"
*
* @param url 请求地址
* @param param Map格式的参数
* @return
*/
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, getDefaultCharSet());
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), getDefaultCharSet());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
/**
* 发送post请求
* @param url
* @param soapRequestXml
* @return
* @throws Exception
*/
public static String sendPostSoapXml(String url, String soapRequestXml) throws Exception {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectionRequestTimeout(60000)
.setConnectTimeout(60000)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//设置post请求方式为SOAP+XML
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
StringEntity data = new StringEntity(soapRequestXml, Charset.forName("UTF-8"));
httpPost.setEntity(data);
//发送post请求
response = closeableHttpClient.execute(httpPost);
if (response == null || response.getStatusLine() == null) {
throw new RuntimeException("发送POST请求失败,返回结果为空!");
}
//返回状态是否200
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
//得到请求结果
HttpEntity entityRes = response.getEntity();
if (entityRes != null) {
String responsetData = EntityUtils.toString(entityRes, "UTF-8");
return responsetData;
}
} else {
throw new Exception("发送POST-SOAP+XML请求出错:" + response);
}
} catch (Exception e) {
throw new Exception("发送POST请求出现异常,"+e.getMessage());
} finally {
try {
// 关闭连接释放资源
if (response != null) {
response.close();
}
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
// public static void main(String[] args) {
// String url = "http://139.215.216.41:9003/prod-api/system/HueinanCommunity/listbuilding/959146767543947264";
// try {
//
// doGet(url );
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* 发送post请求
* @param url
* @param requestJson
* @return
* @throws Exception
*/
public static String sendPostJson(String url, String requestJson) throws Exception {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectionRequestTimeout(60000)
.setConnectTimeout(60000)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//设置post请求方式为JSON
StringEntity data = new StringEntity(requestJson, "UTF-8");
data.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(data);
//发送post请求
response = closeableHttpClient.execute(httpPost);
if (response == null || response.getStatusLine() == null) {
throw new Exception("发送POST请求失败,返回结果为空!");
}
//返回状态是否200
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
//得到请求结果
HttpEntity entityRes = response.getEntity();
if (entityRes != null) {
String responsetData = EntityUtils.toString(entityRes, "UTF-8");
return responsetData;
}
} else {
throw new Exception("发送POST-JSON请求出错:" + response);
}
} catch (Exception e) {
throw new Exception("发送POST请求出现异常,"+e.getMessage());
} finally {
try {
// 关闭连接释放资源
if (response != null) {
response.close();
}
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public static String encryptBASE64(String username, String password) {
byte[] key = (username+":"+password).getBytes();
return new String(Base64.encodeBase64(key));
}
/**
* 设置编码格式utf-8,防止乱码
*
* @return utf-8
*/
private static String getDefaultCharSet() {
OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());
String enc = writer.getEncoding();
return enc;
}
}
更多推荐
所有评论(0)