自定义发送http请求工具
可以自己这是发送请求类别、设置header和设置请求体。
public class HttpUtil {
/**
*
*@desc 发送请求
*@param url 请求地址
*@param method 请求方法
*@param headers 设置头
*@param body 设置请求体
*@return com.alibaba.fastjson.JSONObject
*@author zg-bill
*@date 2022-03-29 10:03:33
*/
public static JSONObject send(String url, String method, Map<String, Object> headers, JSONObject body){
try{
StringBuffer sbf = new StringBuffer();
String strRead = null;
URL requestUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)requestUrl.openConnection();
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setDoOutput(true);
// 设置headers
for (Map.Entry<String, Object> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(),entry.getValue().toString());
}
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
// 设置body
writer.write(body.toString());
writer.flush();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
while ((strRead = reader.readLine()) != null){
sbf.append(strRead);
}
reader.close();
connection.disconnect();
return JSONObject.parseObject(sbf.toString());
}catch (Exception e){
e.printStackTrace();
log.info("发送【{},{}】请求失败!",url,method);
}
return null;
}
}