HttpUtil.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.uas.ps.message.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. /**
  9. * HTTP工具类,封装http请求
  10. *
  11. * @author suntg
  12. * @date 2015年3月5日14:20:40
  13. */
  14. public class HttpUtil {
  15. /**
  16. * 暂时先使用这种方法(短信接口调用)
  17. * @param url url
  18. * @param param param
  19. * @return
  20. */
  21. public static String sendPost(String url, String param) {
  22. PrintWriter out = null;
  23. BufferedReader in = null;
  24. String result = "";
  25. try {
  26. URL realUrl = new URL(url);
  27. // 打开和URL之间的连接
  28. URLConnection conn = realUrl.openConnection();
  29. // 设置通用的请求属性
  30. conn.setRequestProperty("content-type", "application/json");
  31. conn.setRequestProperty("accept", "*/*");
  32. conn.setRequestProperty("connection", "Keep-Alive");
  33. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  34. // 发送POST请求必须设置如下两行
  35. conn.setDoOutput(true);
  36. conn.setDoInput(true);
  37. // 获取URLConnection对象对应的输出流
  38. out = new PrintWriter(conn.getOutputStream());
  39. // 发送请求参数
  40. out.print(param);
  41. // flush输出流的缓冲
  42. out.flush();
  43. // 定义BufferedReader输入流来读取URL的响应
  44. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  45. String line;
  46. while ((line = in.readLine()) != null) {
  47. result += line;
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. // 使用finally块来关闭输出流、输入流
  53. finally {
  54. try {
  55. if (out != null) {
  56. out.close();
  57. }
  58. if (in != null) {
  59. in.close();
  60. }
  61. } catch (IOException ex) {
  62. ex.printStackTrace();
  63. }
  64. }
  65. return result;
  66. }
  67. }