当前位置:   article > 正文

Java实现发送post请求,RestTemplate发送post请求,Httpclient发送post请求_java使用resttemplate发送post请求

java使用resttemplate发送post请求
  1. 一、JAVA 使用RestTemplate发送post请求
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.http.HttpEntity;
  7. import org.springframework.http.HttpHeaders;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.web.client.RestClientException;
  11. import org.springframework.web.client.RestTemplate;
  12. @Service
  13. @Slf4j
  14. public class TestServiceImpl implements TestService {
  15. @Autowired
  16. private RestTemplate restTemplate;
  17. private final String URL = "http://15.15.82.127:8124/api/test/getData";
  18. private final String USER_NAME = "test";
  19. private final String PASS_WORD = "test123";
  20. 第一种方法
  21. //RestTemplate发送POST请求之带header,入参为json格式
  22. @Override
  23. public String getData(){
  24. //1、构建body参数
  25. JSONObject jsonObject = new JSONObject();
  26. jsonObject.put("UserName",USER_NAME);
  27. jsonObject.put("Password",PASS_WORD);
  28. //2、添加请求头
  29. HttpHeaders headers = new HttpHeaders();
  30. headers.add("Content-Type","application/json");
  31. //3、组装请求头和参数
  32. HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(jsonObject), headers);
  33. //4、发起post请求
  34. ResponseEntity<String> stringResponseEntity = null;
  35. try {
  36. stringResponseEntity = restTemplate.postForEntity(URL, formEntity, String.class);
  37. log.info("ResponseEntity----"+stringResponseEntity);
  38. } catch (RestClientException e) {
  39. e.printStackTrace();
  40. }
  41. //5、获取http状态码
  42. int statusCodeValue = stringResponseEntity.getStatusCodeValue();
  43. log.info("httpCode-----"+statusCodeValue);
  44. //6、获取返回体
  45. String body = stringResponseEntity.getBody();
  46. log.info("body-----"+body);
  47. //7、映射实体类
  48. Wrapper wrapper = JSONObject.parseObject(body, Wrapper.class);
  49. String data = wrapper.getData();
  50. log.info("data-----"+data);
  51. return data;
  52. }
  53. 第二种方法
  54. //RestTemplate发送POST请求之formData形式
  55. @Override
  56. public String getData2(){
  57. MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();;
  58. reqMap.add("name","huhansan");
  59. reqMap.add("sex","man");
  60. //.postForEntity(url,请求数据,返回数据类型)
  61. return restTemplate.postForEntity("http://localhost:8888/postwithpara", reqMap, String.class).getBody();
  62. }
  63. }
  64. 二、Java 使用Httpclient发送post请求
  65. public void post(String url, Map<String, Object> params) {
  66. //创建httppost对象
  67. HttpPost post = new HttpPost(url);
  68. String paramStr = JSON.toJSONString(params);
  69. StringEntity stringEntity = new StringEntity(paramStr, StandardCharsets.UTF_8);
  70. //请求参数
  71. post.setEntity(stringEntity);
  72. //请求头
  73. post.setHeader("Content-Type", "application/json;charset=UTF-8");
  74. String msg = null;
  75. InetAddress ipaddr;
  76. try {
  77. //设置长/短连接 此处为短连接
  78. post.setHeader(HttpHeaders.CONNECTION, HTTP.CONN_CLOSE);
  79. //通过hostname获取本机ip地址
  80. ipaddr = InetAddress.getLocalHost();
  81. post.addHeader(new BasicHeader("API-RemoteIP", ipaddr.getHostAddress()));
  82. //创建httpclient对象发送post请求
  83. CloseableHttpClient httpClient = HttpClients.createDefault();
  84. CloseableHttpResponse resp = httpClient.execute(post);
  85. try {
  86. //返回信息
  87. HttpEntity entity = resp.getEntity();
  88. //获取请求状态码
  89. int statusCode = resp.getStatusLine().getStatusCode();
  90. if (entity != null) {
  91. msg = EntityUtils.toString(entity);
  92. //输出日志
  93. logger.info("url:" + url + "参数:" + params.toString() + "返回信息:" + msg);
  94. }
  95. if (statusCode != 200 && statusCode != 302) {
  96. //输出日志
  97. logger.info("url:" + url + "失败信息:" + msg);
  98. }
  99. } finally {
  100. resp.close();
  101. }
  102. } catch (Exception e) {
  103. e.printStackTrace();
  104. throw new RuntimeException(e.getMessage(), e);
  105. } finally {
  106. post.reset();
  107. post.releaseConnection();
  108. }
  109. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/302855
推荐阅读
相关标签
  

闽ICP备14008679号