HttpUtil.java 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package com.yihu.wlyy.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.io.PrintWriter;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.message.BasicNameValuePair;
  14. import org.json.JSONObject;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. /*
  18. * MD5 算法
  19. */
  20. public class HttpUtil {
  21. private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
  22. /**
  23. * 向指定URL发送GET方法的请求
  24. *
  25. * @param url
  26. * 发送请求的URL
  27. * @param param
  28. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  29. * @return URL 所代表远程资源的响应结果
  30. */
  31. public static String sendGet(String url, String param) {
  32. String result = "";
  33. BufferedReader in = null;
  34. try {
  35. String urlNameString = url + "?" + param;
  36. URL realUrl = new URL(urlNameString);
  37. // 打开和URL之间的连接
  38. URLConnection connection = realUrl.openConnection();
  39. // 设置通用的请求属性
  40. connection.setRequestProperty("accept", "*/*");
  41. connection.setRequestProperty("connection", "Keep-Alive");
  42. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  43. // 建立实际的连接
  44. connection.connect();
  45. // 定义 BufferedReader输入流来读取URL的响应
  46. in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  47. String line;
  48. while ((line = in.readLine()) != null) {
  49. result += line;
  50. }
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. } finally {
  54. try {
  55. if (in != null) {
  56. in.close();
  57. }
  58. } catch (Exception e2) {
  59. e2.printStackTrace();
  60. }
  61. }
  62. return result;
  63. }
  64. /**
  65. * 向指定 URL 发送POST方法的请求
  66. *
  67. * @param url
  68. * 发送请求的 URL带上参数
  69. * @param param
  70. * POST参数。
  71. * @return 所代表远程资源的响应结果
  72. */
  73. public static String sendPost(String url, String param) {
  74. StringBuffer buffer = new StringBuffer();
  75. PrintWriter out = null;
  76. BufferedReader in = null;
  77. HttpURLConnection conn = null;
  78. try {
  79. URL realUrl = new URL(url);
  80. // 打开和URL之间的连接
  81. conn = (HttpURLConnection) realUrl.openConnection();
  82. conn.setRequestMethod("POST");
  83. conn.setConnectTimeout(5000);
  84. conn.setDoOutput(true);
  85. conn.setDoInput(true);
  86. conn.setUseCaches(false);
  87. conn.setRequestProperty("Content-Type", "application/text");
  88. conn.setRequestProperty("accept", "*/*");
  89. conn.setRequestProperty("connection", "Keep-Alive");
  90. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  91. OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
  92. osw.write(param.toString());
  93. osw.flush();
  94. // 读取返回内容
  95. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  96. String temp;
  97. while ((temp = br.readLine()) != null) {
  98. buffer.append(temp);
  99. buffer.append("\n");
  100. }
  101. } catch (Exception e) {
  102. logger.error("push message error:", e);
  103. } finally {
  104. try {
  105. if (out != null) {
  106. out.close();
  107. }
  108. if (in != null) {
  109. in.close();
  110. }
  111. } catch (IOException ex) {
  112. ex.printStackTrace();
  113. }
  114. }
  115. return buffer.toString();
  116. }
  117. /**
  118. * 消息推送
  119. *
  120. * @param receiver 消息接收人
  121. * @param msgType 消息类型
  122. * @param title 消息标题
  123. * @param msg 消息内容
  124. * @param data 消息数据
  125. */
  126. public static boolean pushMessage(String receiver, String msgType, String title, String msg, String data) {
  127. try{
  128. JSONObject sessionObj = createSession(receiver);
  129. JSONObject params = new JSONObject();
  130. sendIM("system","系统",String.valueOf(sessionObj.get("id")),msgType, msg);
  131. return true;
  132. }catch (Exception e){
  133. e.printStackTrace();
  134. }
  135. return false;
  136. }
  137. /**
  138. * 发送消息给IM
  139. *
  140. * @param from 来自
  141. * @param contentType 1文字 2图片消息
  142. * @param content 内容
  143. */
  144. private static String sendIM(String from,String fromName, String sessionId, String contentType, String content) {
  145. String imAddr = SystemConf.getInstance().getImListGet() + "/api/v2/sessions/"+sessionId+"/messages";
  146. JSONObject params = new JSONObject();
  147. params.put("sender_id", from);
  148. params.put("sender_name", fromName);
  149. params.put("business_type", contentType);
  150. params.put("content_type", 1);
  151. params.put("content", content);
  152. params.put("sessionId", sessionId);;
  153. String response = HttpClientUtil.postBody(imAddr, params);
  154. return response;
  155. }
  156. /**
  157. * 创建会话(system)
  158. *
  159. */
  160. private static JSONObject createSession(String receiver) {
  161. String imAddr = SystemConf.getInstance().getImListGet() + "api/v2/sessions";
  162. String participants[]=new String[]{"system:0",receiver+":"+"0"};
  163. JSONObject params = new JSONObject();
  164. params.put("participants", participants);
  165. params.put("session_name", "系统消息");
  166. params.put("session_type", 0);
  167. String ret = HttpClientUtil.postBody(imAddr,params);
  168. JSONObject obj = null;
  169. try{
  170. obj = new JSONObject(ret);
  171. }catch (Exception e){
  172. return null;
  173. }
  174. return obj;
  175. }
  176. /**
  177. * 发送消息到websocket服务器,然后由websocket服务器中转给微信端
  178. * @param userid 接收数据的患者id
  179. * @param data 内容
  180. * @return 推送成功:{"errno":"0","errmsg":""},推送失败:{"errno":"1","errmsg":"User is not online"}
  181. * @author shenzaixin
  182. */
  183. public static String sendWeixinWebsocketMsg(String userid,String data){
  184. PrintWriter out = null;
  185. BufferedReader in = null;
  186. HttpURLConnection conn = null;
  187. try {
  188. System.out.println("consult-send:" + userid + ":" + data);
  189. String url = SystemConf.getInstance().getWeixinWebsocketServer() + "?userid=" + userid + "&data=" + data;
  190. URL realUrl = new URL(url);
  191. // 打开和URL之间的连接
  192. conn = (HttpURLConnection) realUrl.openConnection();
  193. conn.setRequestMethod("GET");
  194. conn.setDoOutput(true);
  195. conn.setDoInput(true);
  196. conn.setUseCaches(false);
  197. conn.setRequestProperty("Content-Type", "application/json");
  198. // OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
  199. // osw.write(param.toString());
  200. // osw.flush();
  201. // 读取返回内容
  202. StringBuffer buffer = new StringBuffer();
  203. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  204. String temp;
  205. while ((temp = br.readLine()) != null) {
  206. buffer.append(temp);
  207. }
  208. System.out.println(buffer.toString());
  209. JSONObject json = new JSONObject(buffer.toString());
  210. System.out.println("consult-reply:" + json.toString());
  211. return json.toString();
  212. } catch (Exception e) {
  213. logger.error("push message error:", e);
  214. return "{\"errno\":\"1\",\"errmsg\":\""+e.getMessage()+"\"}";
  215. } finally {
  216. try {
  217. if (out != null) {
  218. out.close();
  219. }
  220. if (in != null) {
  221. in.close();
  222. }
  223. } catch (IOException ex) {
  224. ex.printStackTrace();
  225. }
  226. }
  227. }
  228. /**
  229. * 向指定 URL 发送POST方法的请求
  230. *
  231. * @param url 发送请求的 URL带上参数
  232. * @param param POST参数。
  233. * @param charset 编码格式
  234. * @return 所代表远程资源的响应结果
  235. */
  236. public static String sendPost(String url, String param, String charset) {
  237. StringBuffer buffer = new StringBuffer();
  238. PrintWriter out = null;
  239. BufferedReader in = null;
  240. HttpURLConnection conn = null;
  241. try {
  242. URL realUrl = new URL(url);
  243. // 打开和URL之间的连接
  244. conn = (HttpURLConnection) realUrl.openConnection();
  245. conn.setRequestMethod("POST");
  246. conn.setDoOutput(true);
  247. conn.setDoInput(true);
  248. conn.setUseCaches(false);
  249. conn.setRequestProperty("Content-Type", "application/text");
  250. conn.setRequestProperty("accept", "*/*");
  251. conn.setRequestProperty("connection", "Keep-Alive");
  252. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  253. OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), charset);
  254. osw.write(param.toString());
  255. osw.flush();
  256. // 读取返回内容
  257. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
  258. String temp;
  259. while ((temp = br.readLine()) != null) {
  260. buffer.append(temp);
  261. buffer.append("\n");
  262. }
  263. } catch (Exception e) {
  264. logger.error("push message error:", e);
  265. } finally {
  266. try {
  267. if (out != null) {
  268. out.close();
  269. }
  270. if (in != null) {
  271. in.close();
  272. }
  273. } catch (IOException ex) {
  274. ex.printStackTrace();
  275. }
  276. }
  277. return buffer.toString();
  278. }
  279. public static void main(String[] args) {
  280. boolean result = HttpUtil.pushMessage("U20160322000001", "1", "您有一条医嘱提醒", "少吃辣,多运动,多吃水果!", null);
  281. System.out.println(result);
  282. }
  283. }