Http方式接口post调用工具 HttpUtil

刺骨的言语ヽ痛彻心扉 2022-04-12 02:28 996阅读 1赞

工作中有时候需要调用外部的接口,通过http方式调用,记录一下这个工具类。

  1. public class HttpUtil {
  2. private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
  3. private final static int CONNECT_TIMEOUT = 50000;
  4. private static final String CONTENT_TYPE = "application/xml";
  5. private static final String DEFAULT_ENCODING = "UTF-8";
  6. /**
  7. * post请求,参数格式设置为xml
  8. * @param urlStr
  9. * @param data
  10. * @return
  11. */
  12. public static String postData(String urlStr, String data, String contentType) {
  13. BufferedReader reader = null;
  14. try {
  15. URL url = new URL(urlStr);
  16. URLConnection conn = url.openConnection();
  17. conn.setDoOutput(true);
  18. conn.setConnectTimeout(CONNECT_TIMEOUT);
  19. conn.setReadTimeout(CONNECT_TIMEOUT);
  20. if (contentType != null) {
  21. conn.setRequestProperty("content-type", contentType);
  22. }
  23. OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
  24. if (data == null) {
  25. writer.write("");
  26. } else {
  27. writer.write(data);
  28. }
  29. writer.flush();
  30. writer.close();
  31. reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),DEFAULT_ENCODING));
  32. StringBuilder sb = new StringBuilder();
  33. String line = null;
  34. while ((line = reader.readLine()) != null) {
  35. sb.append(line);
  36. sb.append("\r\n");
  37. }
  38. return sb.toString();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. log.error(e.getMessage());
  42. } finally {
  43. try {
  44. if (reader != null) {
  45. reader.close();
  46. }
  47. } catch (IOException e) {
  48. log.error(e.getMessage());
  49. }
  50. }
  51. return null;
  52. }
  53. }

发表评论

表情:
评论列表 (有 0 条评论,996人围观)

还没有评论,来说两句吧...

相关阅读