一、再Java系统开发中,网络编程是绕不开的技能之一,也就是发送请求和接收请求的处理。最常用的就是我们经常说的post请求,get请求这些东西。系统在调用别的系统的接口时无一不是通过网络。各种do get do post。
再spring框架中我们常用的fegin就是一种网络编程的封装。
有时我们也可以自己封装自己的网络请求工具类
例如:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
/**
* http请求
*/
@Slf4j
public class HttpUtils {
public static String doGet(String url) {
return doGet(url, null);
}
public static String doGet(String url, Map<String, String> map) {
String resultString = "";
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 参数设置
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
if (CollectionUtil.isNotEmpty(map)) {
for (String key : map.keySet()) {
params.add(key, map.get(key));
}
}
try {
// 设置表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
params, headers);
// 执行HTTP请求
ResponseEntity<String> response = client.exchange(url, HttpMethod.GET, requestEntity, String.class);
resultString = response.getBody();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPost(String url, Map<String, String> map) {
String resultString = "";
ResponseEntity<String> response = null;
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 参数设置
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
if (CollectionUtil.isNotEmpty(map)) {
for (String key : map.keySet()) {
params.add(key, map.get(key));
}
}
try {
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
params, headers);
// 执行HTTP请求
response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
resultString = response.getBody();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return resultString;
}
public static String doPostJson(String url, String json) {
String resultString = "";
RestTemplate client = new RestTemplate();
ResponseEntity<String> response = null;
// 提交方式设置
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
try {
// 执行HTTP请求
response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
resultString = response.getBody();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
} catch (Exception e) {
// TODO Auto-generated catch block
log.error(e.getMessage(), e);
}
}
return resultString;
}
/**
* 创建http请求头
* @param url
* @return
* @throws Exception
*/
public static URLConnection FactoryCreatURLConnection(String url) throws Exception {
URL realUrl;
URLConnection conn = null;
try {
// 打开和URL之间的连接
realUrl = new URL(url);
conn = realUrl.openConnection();
conn.setRequestProperty("accept", "text/plain;charset=utf-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
if (StringUtils.isEmpty(url)) {
return false;
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
// 设置超时时间
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
&& connection.getResponseCode() <= HttpURLConnection.HTTP_VERSION) {
return true;
}
} catch (Exception e) {
log.error(" HttpURLConnection exception happend!");
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return false;
}
/**
* 判断ip是否能ping通
*/
public static boolean checkIp(String ipAddr) {
try {
boolean status = false;
if (!StringUtils.isEmpty(ipAddr)) {
int timeOut = 3000; // 超时 3秒
status = InetAddress.getByName(ipAddr).isReachable(timeOut);
return status;
}
return status;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
package cn.ctg.common.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
/**
* http请求
*/
@Slf4j
public class HttpUtils {
public static String doGet(String url) {
return doGet(url, null);
}
public static String doGet(String url, Map<String, String> map) {
String resultString = "";
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 参数设置
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
if (CollectionUtil.isNotEmpty(map)) {
for (String key : map.keySet()) {
params.add(key, map.get(key));
}
}
try {
// 设置表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
params, headers);
// 执行HTTP请求
ResponseEntity<String> response = client.exchange(url, HttpMethod.GET, requestEntity, String.class);
resultString = response.getBody();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPost(String url, Map<String, String> map) {
String resultString = "";
ResponseEntity<String> response = null;
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 参数设置
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
if (CollectionUtil.isNotEmpty(map)) {
for (String key : map.keySet()) {
params.add(key, map.get(key));
}
}
try {
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
params, headers);
// 执行HTTP请求
response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
resultString = response.getBody();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return resultString;
}
public static String doPostJson(String url, String json) {
String resultString = "";
RestTemplate client = new RestTemplate();
ResponseEntity<String> response = null;
// 提交方式设置
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
try {
// 执行HTTP请求
response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
resultString = response.getBody();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
} catch (Exception e) {
// TODO Auto-generated catch block
log.error(e.getMessage(), e);
}
}
return resultString;
}
/**
* 创建http请求头
* @param url
* @return
* @throws Exception
*/
public static URLConnection FactoryCreatURLConnection(String url) throws Exception {
URL realUrl;
URLConnection conn = null;
try {
// 打开和URL之间的连接
realUrl = new URL(url);
conn = realUrl.openConnection();
conn.setRequestProperty("accept", "text/plain;charset=utf-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
/**
* 判断连接是否可用
*
* @param url http请求地址
* @return
*/
public static boolean isRearchUrl(String url) {
return isRearchUrl(url, 3000);
}
/**
* 判断连接是否可用
*
* @param url http请求地址
* @return
*/
public static boolean isRearchUrl(String url, int timeout) {
if (StringUtils.isEmpty(url)) {
return false;
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
// 设置超时时间
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
&& connection.getResponseCode() <= HttpURLConnection.HTTP_VERSION) {
return true;
}
} catch (Exception e) {
log.error(" HttpURLConnection exception happend!");
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return false;
}
/**
* 判断ip是否能ping通
*/
public static boolean checkIp(String ipAddr) {
try {
boolean status = false;
if (!StringUtils.isEmpty(ipAddr)) {
int timeOut = 3000; // 超时 3秒
status = InetAddress.getByName(ipAddr).isReachable(timeOut);
return status;
}
return status;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容