HTTP POST方式 这种方式写存在什么问题?

滴嘟嘟嘟滴嘟 2020-11-25 04:44:41
http://xx.xx.xx.xx:xxxx/aa?Body=msg

String httpRes = "";// 获取结果
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;

String url = "http://xx.x.x:x/aa";

String msg = “”

try {
httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);

RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(3000).build();
post.setConfig(requestConfig);

String Body= URLEncoder.encode(msg, "UTF-8");

//构建内容
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("Body", Body));
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");

// 发送的数据请求
post.addHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
post.setEntity(entity);
try {
response = httpClient.execute(post);
// 从response中取出HttpEntity对象
HttpEntity entity1 = response.getEntity();
httpRes = EntityUtils.toString(entity1, "UTF-8");

EntityUtils.consume(response.getEntity());// 完全消耗
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != response)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放链接
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}

return httpRes;

...全文
11791 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kk1924 2020-12-23
  • 打赏
  • 举报
回复
引用 4 楼 吃不胖的茶叶蛋 的回复:
[quote=引用 3 楼 捏造的信仰 的回复:]楼主要学会贴代码:

正确的代码是这样的:
public class Hello {
private String name;
}


哪哪都是你--真有你的[/quote]


我觉得你是不是搞了一个机器人
  • 打赏
  • 举报
回复
引用 3 楼 捏造的信仰 的回复:
楼主要学会贴代码: 正确的代码是这样的:
public class Hello {
    private String name;
}
哪哪都是你--真有你的
捏造的信仰 2020-12-04
  • 打赏
  • 举报
回复
楼主要学会贴代码:

正确的代码是这样的:
public class Hello {
private String name;
}
生财 2020-12-03
  • 打赏
  • 举报
回复
报什么错误呢?
  • 打赏
  • 举报
回复
EntityUtils.consume写finally,否则存在资源泄露风险

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧