package com.cf.uli.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* http 请求工具
*/
public class HttpSendUtil {
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
String jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
//httpUrlConn.setRequestMethod(requestMethod);
httpUrlConn.setUseCaches(true);
if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("utf-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = buffer.toString();
} catch (MalformedURLException e) {
//log.error("内部调用get请求方法MalformedURL请求异常: ", e);
} catch (IOException e) {
//log.error("内部调用get请求方法请求IO异常: ", e);
} catch (Exception e) {
//log.error("内部调用get请求方法请求异常: ", e);
}
return jsonObject;
}
}
HTTP请求工具类
于 2022-08-23 18:15:14 首次发布