ApiHttpUtils.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package fi.rim.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import kd.bos.script.annotations.KSObject;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClientBuilder;
  10. import org.apache.http.util.EntityUtils;
  11. @KSObject
  12. public class ApiHttpUtils {
  13. public static String Posthttp(String url, String Params) throws Exception {
  14. // 获得Http客户端
  15. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  16. // 创建Post请求
  17. //设置请求路径
  18. HttpPost httpPost = new HttpPost(url);
  19. httpPost.setHeader("Content-type", "application/json;charset=utf-8");
  20. StringEntity entity = new StringEntity(Params,"UTF-8");
  21. // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
  22. // 设置编码格式
  23. entity.setContentEncoding("UTF-8");
  24. // 发送Json格式的数据请求
  25. entity.setContentType("application/json");
  26. httpPost.setEntity(entity);
  27. // 响应模型(发送post请求)
  28. CloseableHttpResponse response = httpClient.execute(httpPost);
  29. // 从响应模型中获取响应实体
  30. HttpEntity responseEntity = response.getEntity();
  31. com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
  32. if (responseEntity != null) {
  33. jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
  34. return jsonObject.toJSONString();
  35. }
  36. // 释放资源
  37. if (httpClient != null) {
  38. httpClient.close();
  39. }
  40. if (response != null) {
  41. response.close();
  42. }
  43. return "";
  44. }
  45. }