@Slf4j
public class HttpPost{
public static Map<String, Object> request(String url, String content) {
Map<String, Object> result = new HashMap<>();
String errorStr = "";
String status = "";
String response = "";
PrintWriter out = null;
BufferedReader in = null;
try (
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
// 设置请求属性
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("x-adviewrtb-version", "2.1");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
out.write(content);
// flush输出流的缓冲
out.flush();
httpURLConnection.connect();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
response += line;
}
status = Integer.toString(httpURLConnection.getResponseCode());
) catch (Exception e) {
log.error("发送POST请求异常,异常原因:" + e.getCause().toString());
errorStr = e.getCause().toString();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
result.put("errorStr", errorStr);
result.put("status", status);
result.put("response", response);
return result;
}
}
java发起HttpPost请求,工具类
最新推荐文章于 2023-09-07 15:39:38 发布