创建请求工具类:
使用第三方库,如Apache HttpClient:Apache HttpClient是一个功能强大的HTTP客户端库,提供了更便捷的方式发送HTTP请求。文章来源:https://www.toymoban.com/news/detail-861047.html
public class HttpRequest {
// 发送post请求
public JSONObject post(String url, Map data) {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数拼接JOSN字符串
String data_s = mapToString(data);
System.out.println(data_s);
StringEntity entity = new StringEntity(data_s, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
//定义接收数据
JSONObject result = new JSONObject();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
}
} catch (
IOException e) {
e.printStackTrace();
result.put("error", "连接错误!");
}
//关闭连接
try {
client.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
}
构建请求体
为了更好的构建请求体这里我写了一个用于将Map<String, String>转换为字符串的方法。
它遍历Map中的每个键值对,将键和值以key=value的形式拼接,并用&分隔每个键值对。最后,如果字符串的长度大于0,则删除最后一个多余的&符号,然后返回拼接好的字符串。文章来源地址https://www.toymoban.com/news/detail-861047.html
public static String mapToString(Map<String, String> map) {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
stringBuilder.append(key).append("=").append(value).append("&");
}
// 删除最后一个"&"
if (stringBuilder.length() > 0) {
stringBuilder.setLength(stringBuilder.length() - 1);
}
return stringBuilder.toString();
}
HttpRequest 工具类的使用示例:
public Result rtmpaddress(){
String url = "******";
//定义发送数据
Map<String, String> map_rtmp = new HashMap<>();
map_rtmp.put("accessToken", "******");
map_rtmp.put("deviceSerial", "******");
map_rtmp.put("channelNo", "1");
map_rtmp.put("protocol", "3");
HttpRequest httprequest = new HttpRequest();
JSONObject result_rtmp = httprequest.post(url,map_rtmp);
String url_rtmp = (String) result_rtmp.getJSONObject("data").get("url");
if (result_rtmp.get("code").equals("200")) {
return Result.ok().data("url",url_rtmp).data("message",result_rtmp.get("msg"));
} else {
return Result.error().data("message",result_rtmp.get("msg"));
}
}
到了这里,关于在java中发送post请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!