PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/j2se/LGame-j2se-0.2.7/org/loon/framework/game/simple/utils/http/AbstractClient.java

http://loon-simple.googlecode.com/
Java | 507 lines | 365 code | 55 blank | 87 comment | 72 complexity | ac674fcf1c5065f7b12ebc12811778fc MD5 | raw file
  1. package org.loon.framework.game.simple.utils.http;
  2. import java.io.DataOutputStream;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.util.HashMap;
  11. import java.util.Iterator;
  12. import java.util.Map;
  13. import java.util.Set;
  14. import java.util.Map.Entry;
  15. import javax.net.ssl.HostnameVerifier;
  16. import javax.net.ssl.HttpsURLConnection;
  17. import javax.net.ssl.SSLSession;
  18. import org.loon.framework.game.simple.core.LSystem;
  19. import org.loon.framework.game.simple.utils.StringUtils;
  20. import org.loon.framework.game.simple.utils.xml.Ldom;
  21. import org.loon.framework.game.simple.utils.xml.XmlUtils;
  22. import sun.misc.BASE64Encoder;
  23. /**
  24. * Copyright 2008 - 2009
  25. *
  26. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  27. * use this file except in compliance with the License. You may obtain a copy of
  28. * the License at
  29. *
  30. * http://www.apache.org/licenses/LICENSE-2.0
  31. *
  32. * Unless required by applicable law or agreed to in writing, software
  33. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  34. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  35. * License for the specific language governing permissions and limitations under
  36. * the License.
  37. *
  38. * @project loonframework
  39. * @author chenpeng
  40. * @email?ceponline@yahoo.com.cn
  41. * @version 0.1
  42. */
  43. abstract class AbstractClient {
  44. final static private int threadsSize = 2;
  45. final static String POST = "POST";
  46. final static String GET = "GET";
  47. final static String HTTPS = "HTTPS";
  48. protected int timeOut, responseCode, responseLength, bufferedSize;
  49. protected String cookie, method, postData, digest, userName, passWord;
  50. protected HttpURLConnection connection;
  51. protected HashMap cookies;
  52. protected HashMap headerMap;
  53. protected InputStream inputStream;
  54. private HttpHeader header;
  55. private URL open;
  56. private String urlString;
  57. public AbstractClient(String urlString) {
  58. try {
  59. this.urlString = urlString;
  60. this.open(new URL(urlString.startsWith("http://")
  61. || urlString.startsWith("https://")
  62. || urlString.startsWith("ftp://") ? urlString
  63. : ("http://" + urlString).intern()));
  64. } catch (MalformedURLException e) {
  65. }
  66. }
  67. private HostnameVerifier hv = new HostnameVerifier() {
  68. public boolean verify(String urlHostName, SSLSession session) {
  69. return true;
  70. }
  71. };
  72. protected static void trustAllHttpsCertificates() throws Exception {
  73. javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
  74. javax.net.ssl.TrustManager tm = new Trust();
  75. trustAllCerts[0] = tm;
  76. javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
  77. .getInstance("SSL");
  78. sc.init(null, trustAllCerts, null);
  79. javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
  80. .getSocketFactory());
  81. }
  82. public static class Trust implements javax.net.ssl.TrustManager,
  83. javax.net.ssl.X509TrustManager {
  84. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  85. return null;
  86. }
  87. public boolean isServerTrusted(
  88. java.security.cert.X509Certificate[] certs) {
  89. return true;
  90. }
  91. public boolean isClientTrusted(
  92. java.security.cert.X509Certificate[] certs) {
  93. return true;
  94. }
  95. public void checkServerTrusted(
  96. java.security.cert.X509Certificate[] certs, String authType)
  97. throws java.security.cert.CertificateException {
  98. return;
  99. }
  100. public void checkClientTrusted(
  101. java.security.cert.X509Certificate[] certs, String authType)
  102. throws java.security.cert.CertificateException {
  103. return;
  104. }
  105. }
  106. public AbstractClient(URL url) {
  107. open(url);
  108. }
  109. private void open(URL url) {
  110. this.cookies = new HashMap();
  111. this.open = url;
  112. this.header = new HttpHeader();
  113. this.method = "GET";
  114. this.headerMap = new HashMap();
  115. this.timeOut = 180000;
  116. }
  117. private void postCookies() {
  118. StringBuffer sbr = new StringBuffer();
  119. Iterator it = cookies.entrySet().iterator();
  120. do {
  121. if (!it.hasNext()) {
  122. break;
  123. }
  124. Entry entry = (Entry) it.next();
  125. sbr.append(entry.getKey());
  126. sbr.append("=");
  127. sbr.append(entry.getValue());
  128. if (it.hasNext()) {
  129. sbr.append("; ");
  130. }
  131. } while (true);
  132. if (sbr.length() > 0) {
  133. connection.setRequestProperty("Cookie", cookie = sbr.toString());
  134. header.setCookie(cookie);
  135. }
  136. }
  137. public void begin() {
  138. try {
  139. boolean foundRedirect;
  140. do {
  141. if (HTTPS.equalsIgnoreCase(open.getProtocol())) {
  142. trustAllHttpsCertificates();
  143. HttpsURLConnection.setDefaultHostnameVerifier(hv);
  144. connection = (HttpsURLConnection) open.openConnection();
  145. } else {
  146. connection = (HttpURLConnection) open.openConnection();
  147. // ??Cookies
  148. postCookies();
  149. }
  150. if (digest != null) {
  151. connection.setRequestProperty("Authorization", digest);
  152. }
  153. connection.setDoOutput(POST.equalsIgnoreCase(method));
  154. connection.setDoInput(true);
  155. connection.setUseCaches(false);
  156. connection.setInstanceFollowRedirects(false);
  157. // ????
  158. if (timeOut > 0) {
  159. System.setProperty("sun.net.client.defaultConnectTimeout",
  160. String.valueOf(timeOut));
  161. System.setProperty("sun.net.client.defaultReadTimeout",
  162. String.valueOf(timeOut));
  163. }
  164. connection.setRequestMethod(method);
  165. connection.setRequestProperty("User-Agent", header
  166. .getUserAgentValue());
  167. connection
  168. .setRequestProperty(
  169. "Accept",
  170. "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
  171. connection.setRequestProperty("Accept-Language", "zh-CN");
  172. connection.setRequestProperty("Accept-Charset",
  173. "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  174. connection.setRequestProperty("Content-type", "text/html");
  175. connection.setRequestProperty("Cache-Control", "no-cache");
  176. if (POST.equalsIgnoreCase(method)) {
  177. connection.setRequestProperty("Content-Type",
  178. "application/x-www-form-urlencoded");
  179. DataOutputStream out = new DataOutputStream(connection
  180. .getOutputStream());
  181. out.writeBytes(postData);
  182. out.flush();
  183. out.close();
  184. }
  185. if (headerMap != null && headerMap.size() > 0) {
  186. Set headersSet = headerMap.entrySet();
  187. for (Iterator it = headersSet.iterator(); it.hasNext();) {
  188. Entry entry = (Entry) it.next();
  189. connection.setRequestProperty((String) entry.getKey(),
  190. (String) entry.getValue());
  191. }
  192. }
  193. // ????
  194. connection.connect();
  195. cookie = connection.getHeaderField("Set-Cookie");
  196. // ??Cookies
  197. setCookies(StringUtils.split(cookie, ';'));
  198. // ??????
  199. responseCode = connection.getResponseCode();
  200. // ?????????
  201. responseLength = connection.getContentLength();
  202. if (responseCode == 302) {
  203. // ???
  204. String location = connection.getHeaderField("Location");
  205. open = new URL(location);
  206. foundRedirect = true;
  207. } else {
  208. if (responseCode == 200 || responseCode == 201) {
  209. inputStream = connection.getInputStream();
  210. } else {
  211. inputStream = connection.getErrorStream();
  212. }
  213. bufferedSize = responseLength == -1 ? 2048 : responseLength;
  214. foundRedirect = false;
  215. }
  216. // ????????
  217. } while (foundRedirect);
  218. } catch (Exception e) {
  219. }
  220. }
  221. /**
  222. * ??????????
  223. *
  224. * @return
  225. */
  226. public int getPort() {
  227. return ((open != null) && (open.getPort() != -1)) ? open.getPort() : 80;
  228. }
  229. /**
  230. * ??????
  231. *
  232. * @return
  233. */
  234. public HttpURLConnection getConnection() {
  235. try {
  236. if (HTTPS.equalsIgnoreCase(open.getProtocol())) {
  237. trustAllHttpsCertificates();
  238. HttpsURLConnection.setDefaultHostnameVerifier(hv);
  239. connection = (HttpsURLConnection) open.openConnection();
  240. } else {
  241. connection = (HttpURLConnection) open.openConnection();
  242. }
  243. } catch (Exception e) {
  244. e.printStackTrace();
  245. }
  246. return connection;
  247. }
  248. /**
  249. * ?????????????
  250. *
  251. * @return
  252. */
  253. public boolean exists() {
  254. File file = new File(getFileName());
  255. if (!file.exists()) {
  256. return false;
  257. }
  258. int size = -1;
  259. try {
  260. HttpURLConnection connection = getConnection();
  261. connection.connect();
  262. size = connection.getContentLength();
  263. connection.disconnect();
  264. } catch (Exception e) {
  265. }
  266. return size == file.length();
  267. }
  268. /**
  269. * ????????????
  270. *
  271. * @return
  272. */
  273. public String getFileName() {
  274. if (open == null) {
  275. return null;
  276. }
  277. return open.getPath().substring(open.getPath().lastIndexOf("/") + 1,
  278. open.getPath().length());
  279. }
  280. /**
  281. * ??cookies
  282. *
  283. * @param key
  284. * @param value
  285. * @throws IOException
  286. */
  287. public void setCookie(String key, String value) throws IOException {
  288. cookies.put(key.trim(), value.trim());
  289. }
  290. /**
  291. * ??cookies
  292. *
  293. * @param cookie
  294. * @throws IOException
  295. */
  296. public void setCookies(Map cookie) throws IOException {
  297. if (cookie == null) {
  298. return;
  299. } else {
  300. cookies.putAll(cookie);
  301. return;
  302. }
  303. }
  304. /**
  305. * ??cookies
  306. *
  307. * @param cookie
  308. * @throws IOException
  309. */
  310. public void setCookies(String[] cookie) throws IOException {
  311. if (cookie == null) {
  312. return;
  313. }
  314. try {
  315. for (int i = 0; i < cookie.length; i++) {
  316. String[] ret = cookie[i].split("=");
  317. setCookie(ret[0], ret[1]);
  318. }
  319. } catch (Exception e) {
  320. }
  321. }
  322. public ExternalDownload getExternalDownload() throws Exception {
  323. return getExternalDownload(threadsSize);
  324. }
  325. public ExternalDownload getExternalDownload(String fileName)
  326. throws Exception {
  327. return getExternalDownload(fileName, threadsSize);
  328. }
  329. public ExternalDownload getExternalDownload(int threads) throws Exception {
  330. return getExternalDownload(getFileName(), threadsSize);
  331. }
  332. public ExternalDownload getExternalDownload(String fileName, int threads)
  333. throws Exception {
  334. return getExternalDownload(fileName, getPort(), threadsSize);
  335. }
  336. /**
  337. * ??????????????????
  338. *
  339. * @param fileName
  340. * @param port
  341. * @param threads
  342. * @return
  343. * @throws Exception
  344. */
  345. public ExternalDownload getExternalDownload(final String fileName,
  346. final int port, final int threads) throws Exception {
  347. if (fileName == null || fileName.length() == 0) {
  348. throw new Exception("File address is Unrecognized !");
  349. }
  350. HttpURLConnection connection = getConnection();
  351. File file = new File(fileName);
  352. if (file.exists()) {
  353. file.delete();
  354. }
  355. File tmp_file = new File(fileName + ".tmp");
  356. DownloadInfo info = new DownloadInfo(open.getHost(), open.getFile(),
  357. port, file, connection.getContentLength(), threads, tmp_file);
  358. SocketManager sm = new SocketManager(info);
  359. ExternalDownload down = new ExternalDownload(header, sm);
  360. connection.disconnect();
  361. return down;
  362. }
  363. /**
  364. * ?????????
  365. *
  366. * @return
  367. */
  368. public InternalDownload getInternalDownload() {
  369. return new InternalDownload(this);
  370. }
  371. public String doHTML() {
  372. return doHTML(null);
  373. }
  374. public Ldom doDOM() {
  375. return XmlUtils.getInstance(inputStream);
  376. }
  377. /**
  378. * ????????????
  379. *
  380. * @param encoding
  381. * @return
  382. */
  383. public String doHTML(String encoding) {
  384. if (connection == null) {
  385. return "";
  386. }
  387. try {
  388. if (encoding != null) {
  389. return readString(inputStream, bufferedSize, encoding);
  390. } else {
  391. return readString(inputStream, bufferedSize, LSystem.encoding);
  392. }
  393. } catch (Exception e) {
  394. return e.getMessage();
  395. }
  396. }
  397. private static String readString(final InputStream in, final int size,
  398. final String encoding) throws IOException {
  399. StringBuffer sbr = new StringBuffer();
  400. int nSize = size;
  401. if (nSize == 0) {
  402. nSize = 2048;
  403. }
  404. char[] buffer = new char[nSize];
  405. int offset = 0;
  406. InputStreamReader isr = new InputStreamReader(in, encoding);
  407. while ((offset = isr.read(buffer)) != -1) {
  408. sbr.append(buffer, 0, offset);
  409. }
  410. in.close();
  411. isr.close();
  412. return sbr.toString();
  413. }
  414. public void setParameter(Map parameterMap) {
  415. if (parameterMap != null) {
  416. Set entrySet = parameterMap.entrySet();
  417. for (Iterator it = entrySet.iterator(); it.hasNext();) {
  418. Entry header = (Entry) it.next();
  419. String key = (String) header.getKey();
  420. String value = (String) header.getValue();
  421. if ("user".equals(key)) {
  422. userName = value;
  423. } else if ("pass".equals(key)) {
  424. passWord = value;
  425. } else if ("method".equals(key)) {
  426. method = value;
  427. } else if ("data".equals(key)) {
  428. postData = value;
  429. } else {
  430. headerMap.put(key, value);
  431. }
  432. }
  433. }
  434. if (userName != null && passWord != null) {
  435. BASE64Encoder base64 = new BASE64Encoder();
  436. digest = "Basic "
  437. + base64.encode((userName + ":" + passWord).getBytes());
  438. }
  439. }
  440. public String getURLString() {
  441. return urlString;
  442. }
  443. public URL getURL() {
  444. return open;
  445. }
  446. public void end() {
  447. if (connection != null) {
  448. connection.disconnect();
  449. connection = null;
  450. }
  451. }
  452. }