HttpHelper.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. package com.fourdage.base.common;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStreamWriter;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.HttpURLConnection;
  9. import java.net.Socket;
  10. import java.net.URL;
  11. import java.net.URLConnection;
  12. import java.net.URLEncoder;
  13. import java.util.ArrayList;
  14. import java.util.Iterator;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Map.Entry;
  18. import org.apache.http.HttpResponse;
  19. import org.apache.http.NameValuePair;
  20. import org.apache.http.client.HttpClient;
  21. import org.apache.http.client.entity.UrlEncodedFormEntity;
  22. import org.apache.http.client.methods.HttpGet;
  23. import org.apache.http.client.methods.HttpPost;
  24. import org.apache.http.impl.client.DefaultHttpClient;
  25. import org.apache.http.message.BasicNameValuePair;
  26. public class HttpHelper {
  27. /**
  28. * POST请求
  29. *
  30. * @param urlStr 请求地址
  31. * @param params 参数字典
  32. * @param charset 编码,最好传“UTF-8”
  33. * @return
  34. * @exception RuntimeException
  35. */
  36. public static String sendPostByHttpUrlConnection(String urlStr, Map<String, Object> params, String charset) {
  37. StringBuffer resultBuffer = null;
  38. // 构建请求参数
  39. String sbParams= JoiningTogetherParams(params);
  40. HttpURLConnection con = null;
  41. OutputStreamWriter osw = null;
  42. BufferedReader br = null;
  43. // 发送请求
  44. try {
  45. URL url = new URL(urlStr);
  46. con = (HttpURLConnection) url.openConnection();
  47. con.setRequestMethod("POST");
  48. con.setDoOutput(true);
  49. con.setDoInput(true);
  50. con.setUseCaches(false);
  51. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  52. if (sbParams != null && sbParams.length() > 0) {
  53. osw = new OutputStreamWriter(con.getOutputStream(), charset);
  54. osw.write(sbParams);
  55. osw.flush();
  56. }
  57. // 读取返回内容
  58. resultBuffer = new StringBuffer();
  59. int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
  60. if (contentLength > 0) {
  61. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  62. String temp;
  63. while ((temp = br.readLine()) != null) {
  64. resultBuffer.append(temp);
  65. }
  66. }
  67. } catch (Exception e) {
  68. throw new RuntimeException(e);
  69. } finally {
  70. if (osw != null) {
  71. try {
  72. osw.close();
  73. } catch (IOException e) {
  74. osw = null;
  75. throw new RuntimeException(e);
  76. } finally {
  77. if (con != null) {
  78. con.disconnect();
  79. con = null;
  80. }
  81. }
  82. }
  83. if (br != null) {
  84. try {
  85. br.close();
  86. } catch (IOException e) {
  87. br = null;
  88. throw new RuntimeException(e);
  89. } finally {
  90. if (con != null) {
  91. con.disconnect();
  92. con = null;
  93. }
  94. }
  95. }
  96. }
  97. return resultBuffer.toString();
  98. }
  99. public static String sendPostByUrlConnection(String urlStr, Map<String, Object> params, String charset) {
  100. StringBuffer resultBuffer = null;
  101. // 构建请求参数
  102. String sbParams= JoiningTogetherParams(params);
  103. URLConnection con = null;
  104. OutputStreamWriter osw = null;
  105. BufferedReader br = null;
  106. try {
  107. URL realUrl = new URL(urlStr);
  108. // 打开和URL之间的连接
  109. con = realUrl.openConnection();
  110. // 设置通用的请求属性
  111. con.setRequestProperty("accept", "*/*");
  112. con.setRequestProperty("connection", "Keep-Alive");
  113. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  114. con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  115. // 发送POST请求必须设置如下两行
  116. con.setDoOutput(true);
  117. con.setDoInput(true);
  118. // 获取URLConnection对象对应的输出流
  119. osw = new OutputStreamWriter(con.getOutputStream(), charset);
  120. if (sbParams != null && sbParams.length() > 0) {
  121. // 发送请求参数
  122. osw.write(sbParams);
  123. // flush输出流的缓冲
  124. osw.flush();
  125. }
  126. // 定义BufferedReader输入流来读取URL的响应
  127. resultBuffer = new StringBuffer();
  128. int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
  129. if (contentLength > 0) {
  130. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  131. String temp;
  132. while ((temp = br.readLine()) != null) {
  133. resultBuffer.append(temp);
  134. }
  135. }
  136. } catch (Exception e) {
  137. throw new RuntimeException(e);
  138. } finally {
  139. if (osw != null) {
  140. try {
  141. osw.close();
  142. } catch (IOException e) {
  143. osw = null;
  144. throw new RuntimeException(e);
  145. }
  146. }
  147. if (br != null) {
  148. try {
  149. br.close();
  150. } catch (IOException e) {
  151. br = null;
  152. throw new RuntimeException(e);
  153. }
  154. }
  155. }
  156. return resultBuffer.toString();
  157. }
  158. public static String sendGetByHttpUrlConnection(String urlStr, Map<String, Object> params, String charset) {
  159. StringBuffer resultBuffer = null;
  160. // 构建请求参数
  161. String sbParams= JoiningTogetherParams(params);
  162. HttpURLConnection con = null;
  163. BufferedReader br = null;
  164. try {
  165. URL url = null;
  166. if (sbParams != null && sbParams.length() > 0) {
  167. url = new URL(urlStr + "?" + sbParams);
  168. } else {
  169. url = new URL(urlStr);
  170. }
  171. con = (HttpURLConnection) url.openConnection();
  172. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  173. con.connect();
  174. resultBuffer = new StringBuffer();
  175. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  176. String temp;
  177. while ((temp = br.readLine()) != null) {
  178. resultBuffer.append(temp);
  179. }
  180. } catch (Exception e) {
  181. throw new RuntimeException(e);
  182. } finally {
  183. if (br != null) {
  184. try {
  185. br.close();
  186. } catch (IOException e) {
  187. br = null;
  188. throw new RuntimeException(e);
  189. } finally {
  190. if (con != null) {
  191. con.disconnect();
  192. con = null;
  193. }
  194. }
  195. }
  196. }
  197. return resultBuffer.toString();
  198. }
  199. public static String sendGetByUrlConnection(String urlStr, Map<String, Object> params, String charset) {
  200. StringBuffer resultBuffer = null;
  201. // 构建请求参数
  202. String sbParams= JoiningTogetherParams(params);
  203. BufferedReader br = null;
  204. try {
  205. URL url = null;
  206. if (sbParams != null && sbParams.length() > 0) {
  207. url = new URL(urlStr + "?" + sbParams);
  208. } else {
  209. url = new URL(urlStr);
  210. }
  211. URLConnection con = url.openConnection();
  212. // 设置请求属性
  213. con.setRequestProperty("accept", "*/*");
  214. con.setRequestProperty("connection", "Keep-Alive");
  215. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  216. con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  217. // 建立连接
  218. con.connect();
  219. resultBuffer = new StringBuffer();
  220. br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
  221. String temp;
  222. while ((temp = br.readLine()) != null) {
  223. resultBuffer.append(temp);
  224. }
  225. } catch (Exception e) {
  226. throw new RuntimeException(e);
  227. } finally {
  228. if (br != null) {
  229. try {
  230. br.close();
  231. } catch (IOException e) {
  232. br = null;
  233. throw new RuntimeException(e);
  234. }
  235. }
  236. }
  237. return resultBuffer.toString();
  238. }
  239. public static String httpClientPost(String urlStr, Map<String, Object> params, String charset) {
  240. StringBuffer resultBuffer = null;
  241. HttpClient client = new DefaultHttpClient();
  242. HttpPost httpPost = new HttpPost(urlStr);
  243. // 构建请求参数
  244. List<NameValuePair> list = new ArrayList<NameValuePair>();
  245. Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
  246. while (iterator.hasNext()) {
  247. Entry<String, Object> elem = iterator.next();
  248. list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
  249. }
  250. BufferedReader br = null;
  251. try {
  252. if (list.size() > 0) {
  253. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
  254. httpPost.setEntity(entity);
  255. }
  256. HttpResponse response = client.execute(httpPost);
  257. // 读取服务器响应数据
  258. resultBuffer = new StringBuffer();
  259. br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  260. String temp;
  261. while ((temp = br.readLine()) != null) {
  262. resultBuffer.append(temp);
  263. }
  264. } catch (Exception e) {
  265. throw new RuntimeException(e);
  266. } finally {
  267. if (br != null) {
  268. try {
  269. br.close();
  270. } catch (IOException e) {
  271. br = null;
  272. throw new RuntimeException(e);
  273. }
  274. }
  275. }
  276. return resultBuffer.toString();
  277. }
  278. public static String httpClientGet(String urlStr, Map<String, Object> params, String charset) {
  279. StringBuffer resultBuffer = null;
  280. HttpClient client = new DefaultHttpClient();
  281. BufferedReader br = null;
  282. // 构建请求参数
  283. StringBuffer sbParams = new StringBuffer();
  284. if (params != null && params.size() > 0) {
  285. for (Entry<String, Object> entry : params.entrySet()) {
  286. sbParams.append(entry.getKey());
  287. sbParams.append("=");
  288. try {
  289. sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
  290. } catch (UnsupportedEncodingException e) {
  291. throw new RuntimeException(e);
  292. }
  293. sbParams.append("&");
  294. }
  295. }
  296. if (sbParams != null && sbParams.length() > 0) {
  297. urlStr = urlStr + "?" + sbParams.substring(0, sbParams.length() - 1);
  298. }
  299. HttpGet httpGet = new HttpGet(urlStr);
  300. try {
  301. HttpResponse response = client.execute(httpGet);
  302. // 读取服务器响应数据
  303. br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  304. String temp;
  305. resultBuffer = new StringBuffer();
  306. while ((temp = br.readLine()) != null) {
  307. resultBuffer.append(temp);
  308. }
  309. } catch (Exception e) {
  310. throw new RuntimeException(e);
  311. } finally {
  312. if (br != null) {
  313. try {
  314. br.close();
  315. } catch (IOException e) {
  316. br = null;
  317. throw new RuntimeException(e);
  318. }
  319. }
  320. }
  321. return resultBuffer.toString();
  322. }
  323. public static String sendSocketPost(String urlStr, Map<String, Object> params, String charset) {
  324. String result = "";
  325. // 构建请求参数
  326. StringBuffer sbParams = new StringBuffer();
  327. if (params != null && params.size() > 0) {
  328. for (Entry<String, Object> entry : params.entrySet()) {
  329. sbParams.append(entry.getKey());
  330. sbParams.append("=");
  331. sbParams.append(entry.getValue());
  332. sbParams.append("&");
  333. }
  334. }
  335. Socket socket = null;
  336. OutputStreamWriter osw = null;
  337. InputStream is = null;
  338. try {
  339. URL url = new URL(urlStr);
  340. String host = url.getHost();
  341. int port = url.getPort();
  342. if (-1 == port) {
  343. port = 80;
  344. }
  345. String path = url.getPath();
  346. socket = new Socket(host, port);
  347. StringBuffer sb = new StringBuffer();
  348. sb.append("POST " + path + " HTTP/1.1\r\n");
  349. sb.append("Host: " + host + "\r\n");
  350. sb.append("Connection: Keep-Alive\r\n");
  351. sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
  352. sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
  353. // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
  354. sb.append("\r\n");
  355. if (sbParams != null && sbParams.length() > 0) {
  356. sb.append(sbParams.substring(0, sbParams.length() - 1));
  357. }
  358. osw = new OutputStreamWriter(socket.getOutputStream());
  359. osw.write(sb.toString());
  360. osw.flush();
  361. is = socket.getInputStream();
  362. String line = null;
  363. // 服务器响应体数据长度
  364. int contentLength = 0;
  365. // 读取http响应头部信息
  366. do {
  367. line = readLine(is, 0, charset);
  368. if (line.startsWith("Content-Length")) {
  369. // 拿到响应体内容长度
  370. contentLength = Integer.parseInt(line.split(":")[1].trim());
  371. }
  372. // 如果遇到了一个单独的回车换行,则表示请求头结束
  373. } while (!line.equals("\r\n"));
  374. // 读取出响应体数据(就是你要的数据)
  375. result = readLine(is, contentLength, charset);
  376. } catch (Exception e) {
  377. throw new RuntimeException(e);
  378. } finally {
  379. if (osw != null) {
  380. try {
  381. osw.close();
  382. } catch (IOException e) {
  383. osw = null;
  384. throw new RuntimeException(e);
  385. } finally {
  386. if (socket != null) {
  387. try {
  388. socket.close();
  389. } catch (IOException e) {
  390. socket = null;
  391. throw new RuntimeException(e);
  392. }
  393. }
  394. }
  395. }
  396. if (is != null) {
  397. try {
  398. is.close();
  399. } catch (IOException e) {
  400. is = null;
  401. throw new RuntimeException(e);
  402. } finally {
  403. if (socket != null) {
  404. try {
  405. socket.close();
  406. } catch (IOException e) {
  407. socket = null;
  408. throw new RuntimeException(e);
  409. }
  410. }
  411. }
  412. }
  413. }
  414. return result;
  415. }
  416. public static String sendSocketGet(String urlStr, Map<String, Object> params, String charset) {
  417. String result = "";
  418. // 构建请求参数
  419. StringBuffer sbParams = new StringBuffer();
  420. if (params != null && params.size() > 0) {
  421. for (Entry<String, Object> entry : params.entrySet()) {
  422. sbParams.append(entry.getKey());
  423. sbParams.append("=");
  424. sbParams.append(entry.getValue());
  425. sbParams.append("&");
  426. }
  427. }
  428. Socket socket = null;
  429. OutputStreamWriter osw = null;
  430. InputStream is = null;
  431. try {
  432. URL url = new URL(urlStr);
  433. String host = url.getHost();
  434. int port = url.getPort();
  435. if (-1 == port) {
  436. port = 80;
  437. }
  438. String path = url.getPath();
  439. socket = new Socket(host, port);
  440. StringBuffer sb = new StringBuffer();
  441. sb.append("GET " + path + " HTTP/1.1\r\n");
  442. sb.append("Host: " + host + "\r\n");
  443. sb.append("Connection: Keep-Alive\r\n");
  444. sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
  445. sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
  446. // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
  447. sb.append("\r\n");
  448. if (sbParams != null && sbParams.length() > 0) {
  449. sb.append(sbParams.substring(0, sbParams.length() - 1));
  450. }
  451. osw = new OutputStreamWriter(socket.getOutputStream());
  452. osw.write(sb.toString());
  453. osw.flush();
  454. is = socket.getInputStream();
  455. String line = null;
  456. // 服务器响应体数据长度
  457. int contentLength = 0;
  458. // 读取http响应头部信息
  459. do {
  460. line = readLine(is, 0, charset);
  461. if (line.startsWith("Content-Length")) {
  462. // 拿到响应体内容长度
  463. contentLength = Integer.parseInt(line.split(":")[1].trim());
  464. }
  465. // 如果遇到了一个单独的回车换行,则表示请求头结束
  466. } while (!line.equals("\r\n"));
  467. // 读取出响应体数据(就是你要的数据)
  468. result = readLine(is, contentLength, charset);
  469. } catch (Exception e) {
  470. throw new RuntimeException(e);
  471. } finally {
  472. if (osw != null) {
  473. try {
  474. osw.close();
  475. } catch (IOException e) {
  476. osw = null;
  477. throw new RuntimeException(e);
  478. } finally {
  479. if (socket != null) {
  480. try {
  481. socket.close();
  482. } catch (IOException e) {
  483. socket = null;
  484. throw new RuntimeException(e);
  485. }
  486. }
  487. }
  488. }
  489. if (is != null) {
  490. try {
  491. is.close();
  492. } catch (IOException e) {
  493. is = null;
  494. throw new RuntimeException(e);
  495. } finally {
  496. if (socket != null) {
  497. try {
  498. socket.close();
  499. } catch (IOException e) {
  500. socket = null;
  501. throw new RuntimeException(e);
  502. }
  503. }
  504. }
  505. }
  506. }
  507. return result;
  508. }
  509. private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
  510. List<Byte> lineByte = new ArrayList<Byte>();
  511. byte tempByte;
  512. int cumsum = 0;
  513. if (contentLength != 0) {
  514. do {
  515. tempByte = (byte) is.read();
  516. lineByte.add(Byte.valueOf(tempByte));
  517. cumsum++;
  518. } while (cumsum < contentLength);// cumsum等于contentLength表示已读完
  519. } else {
  520. do {
  521. tempByte = (byte) is.read();
  522. lineByte.add(Byte.valueOf(tempByte));
  523. } while (tempByte != 10);// 换行符的ascii码值为10
  524. }
  525. byte[] resutlBytes = new byte[lineByte.size()];
  526. for (int i = 0; i < lineByte.size(); i++) {
  527. resutlBytes[i] = (lineByte.get(i)).byteValue();
  528. }
  529. return new String(resutlBytes, charset);
  530. }
  531. private static String JoiningTogetherParams(Map<String, Object> params){
  532. StringBuffer sbParams = new StringBuffer();
  533. if (params != null && params.size() > 0) {
  534. for (Entry<String, Object> e : params.entrySet()) {
  535. sbParams.append(e.getKey());
  536. sbParams.append("=");
  537. sbParams.append(e.getValue());
  538. sbParams.append("&");
  539. }
  540. return sbParams.substring(0, sbParams.length() - 1);
  541. }
  542. return "";
  543. }
  544. }