public class HttpRequest {
@Autowired
FileConfigProperties fileConfigProperties;
static Log log = LogFactory.getLog(HttpRequest.class);
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
result=null;
return result;
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url,String param,String token) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Cookie","token="+token);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static String sendPostFromData(String uri, Map<String, Object> textMap) {
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder;
try {
uriBuilder = new URIBuilder(uri);
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "utf-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Iterator<Map.Entry<String, Object>> it = textMap.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("创建连接失败" + e);
} catch (IOException e) {
throw new RuntimeException("创建连接失败" + e);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
/**
* 发送post json数据请求
* @param url 路径
* @param jsonObject 参数(json类型)
* @param encoding 编码格式
* @throws IOException
*/
public static String sendPostjson(String url, JSONObject jsonObject,String encoding) {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
/*RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
httpGet.setConfig(requestConfig);*/
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
httpPost.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
httpPost.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response;
try {
response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
body="";
} catch (IOException e) {
e.printStackTrace();
body="";
}catch (Exception e) {
e.printStackTrace();
body="";
}
return body;
}
/**
* @Description: 添加token
* @Param: url 请求地址 jsonObject 请求参数 encoding编码 token
* @return: String
* @Author: ChangJinhe
* @Date: 2022/9/28
*/
public static String sendPostjson(String url, JSONObject jsonObject,String encoding,String token) {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpPost.setHeader("token",token);
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response;
try {
response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
} catch (ClientProtocolException e) {
body="";
} catch (IOException e) {
body="";
}
return body;
}
public static String sendPostJsonString(HttpPost httpPost, String jsonObject,String encoding) {
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
//HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response;
try {
response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
} catch (ClientProtocolException e) {
body="";
} catch (IOException e) {
body="";
}
return body;
}
public static String readRaw(InputStream inputStream) {
String result = "";
try {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inputStream.close();
result = new String(outSteam.toByteArray(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String GetRandom() {
Integer number=(int) (Math.random()*9999+1);
if(number<10) {
return "000"+number;
}
if(number>=10&&number<100) {
return "00"+number;
}
if(number>=100&&number<1000) {
return "0"+number;
}
if(number>=1000&&number<10000) {
return ""+number;
}
return null;
}
//Object转Map
public static Map<String, Object> getObjectToMap(Object obj) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value;
try {
value = field.get(obj);
if (value == null){
value = "";
}
map.put(fieldName, value);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map;
}
//Map转Object
public static Object mapToObject(Map<Object, Object> map, Class<?> beanClass) {
if (map == null)
return null;
Object obj = null;
try {
obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
if (map.containsKey(field.getName())) {
field.set(obj, map.get(field.getName()));
}
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
public static String okHttpPost(String url,Map<String, String> map,String authorization,String tlinkAppId) {
String data=null;
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(mediaType, "");
String params=buildMap(map);
Request request = new Request.Builder()
.url(url+"?"+params)
.method("POST", body)
.addHeader("authorization", authorization.trim().replace("\r", "").replace("\n", ""))
.addHeader("tlinkAppId", tlinkAppId)
.build();
try {
Response response = client.newCall(request).execute();
return data=response.body().string();
} catch (IOException e) {
return data;
}
}
public static String okHttpGet(String url,JSONObject json,String authorization,String tlinkAppId) {
String data=null;
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
RequestBody body = RequestBody.create(JSON, json.toJSONString());
Request request = new Request.Builder()
.url("https://app.dtuip.com/api/device/getSingleDeviceDatas")
.method("POST", body)
.addHeader("Authorization", authorization.trim().replace("\r", "").replace("\n", ""))
.addHeader("tlinkAppId", tlinkAppId)
.build();
try {
Response response = client.newCall(request).execute();
return data=response.body().string();
} catch (IOException e) {
return data;
}
}
public static String buildMap(Map<String, String> map) {
StringBuffer sb = new StringBuffer();
if (map.size() > 0) {
for (String key : map.keySet()) {
sb.append(key + "=");
if (StringUtils.isEmpty(map.get(key))) {
sb.append("&");
} else {
String value = map.get(key);
try {
value = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sb.append(value + "&");
}
}
}
return sb.toString();
}
public static String md5(String text) {
//加密后的字符串
String encodeStr=DigestUtils.md5Hex(text);
return encodeStr;
}
// 根据传入的密钥进行验证
public static boolean verify(String text, String md5){
String md5str = md5(text);
if (md5str.equalsIgnoreCase(md5)) {
return true;
}
return false;
}
/**
* BASE64解密
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* BASE64加密
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
}