Network.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. package com.usai.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.Socket;
  9. import java.net.URL;
  10. import java.net.UnknownHostException;
  11. import java.security.KeyManagementException;
  12. import java.security.KeyStore;
  13. import java.security.KeyStoreException;
  14. import java.security.NoSuchAlgorithmException;
  15. import java.security.UnrecoverableKeyException;
  16. import java.util.Iterator;
  17. import java.util.Set;
  18. import javax.net.ssl.SSLContext;
  19. import javax.net.ssl.TrustManager;
  20. import javax.net.ssl.X509TrustManager;
  21. import org.apache.http.HttpEntity;
  22. import org.apache.http.HttpResponse;
  23. import org.apache.http.HttpStatus;
  24. import org.apache.http.HttpVersion;
  25. import org.apache.http.client.HttpClient;
  26. import org.apache.http.client.methods.HttpPost;
  27. import org.apache.http.conn.ClientConnectionManager;
  28. import org.apache.http.conn.ConnectTimeoutException;
  29. import org.apache.http.conn.scheme.PlainSocketFactory;
  30. import org.apache.http.conn.scheme.Scheme;
  31. import org.apache.http.conn.scheme.SchemeRegistry;
  32. import org.apache.http.conn.ssl.SSLSocketFactory;
  33. import org.apache.http.entity.mime.HttpMultipartMode;
  34. import org.apache.http.entity.mime.MultipartEntity;
  35. import org.apache.http.entity.mime.content.StringBody;
  36. import org.apache.http.impl.client.DefaultHttpClient;
  37. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  38. import org.apache.http.params.BasicHttpParams;
  39. import org.apache.http.params.HttpConnectionParams;
  40. import org.apache.http.params.HttpParams;
  41. import org.apache.http.params.HttpProtocolParams;
  42. import org.apache.http.protocol.HTTP;
  43. import org.json.JSONException;
  44. import org.json.JSONObject;
  45. import com.usai.apex.ApexTrackingApplication;
  46. import android.content.Context;
  47. import android.content.SharedPreferences.Editor;
  48. import android.database.DatabaseUtils.InsertHelper;
  49. import android.database.sqlite.SQLiteDatabase;
  50. import android.database.sqlite.SQLiteStatement;
  51. import android.net.ConnectivityManager;
  52. import android.net.NetworkInfo;
  53. import android.os.Bundle;
  54. import android.util.Log;
  55. public class Network
  56. {
  57. public static final int BEHAVIOR_SEARCH = 0;
  58. public static final int BEHAVIOR_RESULT = 1;
  59. private static final int REQUEST_TIMEOUT = 5 * 1000;// request time out 20
  60. // secs
  61. private static final int SO_TIMEOUT = 5 * 1000; // so time out 20 secs;
  62. public static int AP_USER_AUTH = 1;
  63. public static int AP_USER_NOT_AUTH = 2;
  64. public static int AP_USER_NOT_EXIST = 3;
  65. public static int AP_SESSION_EXPIRED = 4;
  66. public static int AP_UPLOAD_SUCCESS = 4;
  67. public static int AP_UPLOAD_FAIL = 5;
  68. //
  69. public static final int RESULT_FALSE = 0;
  70. public static final int RESULT_TRUE = -1;
  71. public static final int RESULT_NET_ERROR = -3;
  72. public static final int RESULT_NET_NOTAVAILABLE = -4;
  73. public static final int RESULT_ERROR = -5;
  74. public static final int RESULT_LOCALFILE_ERROR = -7;
  75. public static final int RESULT_USERAUTH_ERROR = -9;
  76. public static final int RESULT_UPDATE_USERAUTH_ERROR = -11;
  77. public static final int RESULT_SESSION_EXPIRED = -13;
  78. // public static final int RESULT_NOCONNECT = 2;
  79. // public static final int RESULT_CONNECT = 3;
  80. // public static final int RESULT_TIMEOUT = 4;
  81. // public static final int RESULT_RESPONSE_NULL= 6;
  82. // public static final int RESULT_ERR_USERAUTH= 8;
  83. // enum RES_VERIFYUSER{RESULT_FALSE,RESULT_TRUE,}
  84. // public static int PROTOCAL_FALSE = 0;
  85. // public static int PROTOCAL_TRUE = 1;
  86. // public static int PROTOCAL_NOT_AUTH = 2;
  87. // public static int PROTOCAL_SUCCESS = 1;
  88. // public static int PROTOCAL_FAILED = 1;
  89. // public static int PROTOCAL_MORE=4;
  90. // public static int ERR_LOCALFILE = 0;
  91. // static String URL_JSON_TEST = "http://192.168.23.1/xampp/json_test.php";
  92. // static String URL_VERIFY_USER =
  93. // "http://192.168.1.10/xampp/verify_user.php";
  94. // static String URL_UPLOAD_PHOTO =
  95. // "http://192.168.1.10/xampp/save_upload_file.php";
  96. // public static String URL_VERIFY_USER =
  97. // "https://ra.apexshipping.com/login.php";
  98. public static String URL_UPDATE_AUTH = "https://ra.apexshipping.com/login.php";
  99. public static String URL_REQUEST_COUNT = "https://ra.apexshipping.com/main.php";
  100. public static String URL_REQUEST_RECORDS = "https://ra.apexshipping.com/main.php";
  101. // public static String FAKE_URL_UPDATE_AUTH =
  102. // "https://192.168.23.1/xampp/auth.json";
  103. // public static String FAKE_SEARCH =
  104. // "https://192.168.23.1/xampp/recordset.json";
  105. // static String URL_UPLOAD_PHOTO =
  106. // "http://192.168.23.1/xampp/save_upload_file.php";
  107. //
  108. // private static String fakegetJson(String url)
  109. // {
  110. // return download(url, 10000);
  111. // // return null;
  112. //
  113. // }
  114. //
  115. // public static String download(String urlStr, int timeout)
  116. // {
  117. // String TAG = "net_dbg@download";
  118. //
  119. // Log.d(TAG, urlStr);
  120. //
  121. // StringBuffer sb = new StringBuffer();
  122. // String line = null;
  123. // BufferedReader buffer = null;
  124. // HttpURLConnection urlConn = null;
  125. // try
  126. // {
  127. // // 创建一个URL对象
  128. // URL url = new URL(urlStr);
  129. // // 创建一个Http连接
  130. // urlConn = (HttpURLConnection) url.openConnection();
  131. //
  132. // urlConn.setConnectTimeout(timeout);
  133. // urlConn.setReadTimeout(timeout);
  134. // // urlConn.connect();
  135. //
  136. // int irespon = urlConn.getResponseCode();
  137. // if (irespon != HttpURLConnection.HTTP_OK)
  138. // {
  139. // Log.e(TAG, "HTTP ERROR CODE " + irespon + " url: " + urlStr);
  140. // urlConn.disconnect();
  141. // return null;
  142. // }
  143. //
  144. // // 使用IO流读取数据
  145. // buffer = new BufferedReader(new InputStreamReader(
  146. // urlConn.getInputStream()));
  147. // while ((line = buffer.readLine()) != null)
  148. // {
  149. // sb.append(line);
  150. // }
  151. // Log.d(TAG, "download success @" + urlStr);
  152. // }
  153. // catch (MalformedURLException e)
  154. // {
  155. // // TODO Auto-generated catch block
  156. // e.printStackTrace();
  157. // }
  158. // catch (IOException e)
  159. // {
  160. // // TODO Auto-generated catch block
  161. // e.printStackTrace();
  162. // }
  163. //
  164. // finally
  165. // {
  166. // try
  167. // {
  168. // if (urlConn != null)
  169. // urlConn.disconnect();
  170. // if (buffer != null)
  171. // buffer.close();
  172. // }
  173. // catch (Exception e)
  174. // {
  175. // e.printStackTrace();
  176. // }
  177. //
  178. // }
  179. // return sb.toString();
  180. // }
  181. private static HttpClient getNewHttpClient()
  182. {
  183. try
  184. {
  185. KeyStore trustStore = KeyStore.getInstance(KeyStore
  186. .getDefaultType());
  187. trustStore.load(null, null);
  188. SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
  189. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  190. HttpParams params = new BasicHttpParams();
  191. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  192. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  193. HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
  194. HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
  195. SchemeRegistry registry = new SchemeRegistry();
  196. registry.register(new Scheme("http", PlainSocketFactory
  197. .getSocketFactory(), 80));
  198. registry.register(new Scheme("https", sf, 443));
  199. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  200. params, registry);
  201. return new DefaultHttpClient(ccm, params);
  202. }
  203. catch (Exception e)
  204. {
  205. return new DefaultHttpClient();
  206. }
  207. }
  208. // HttpClient getHttpsClient()
  209. // {
  210. // KeyStore trustStore;
  211. // try
  212. // {
  213. // trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  214. // trustStore.load(null, null);
  215. // SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  216. // sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  217. //
  218. // SchemeRegistry registry = new SchemeRegistry();
  219. // registry.register(new Scheme("http", PlainSocketFactory
  220. // .getSocketFactory(), 80));
  221. // registry.register(new Scheme("https", sf, 443));
  222. //
  223. // ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  224. // params, registry);
  225. // }
  226. // catch (KeyStoreException e)
  227. // {
  228. // // TODO Auto-generated catch block
  229. // e.printStackTrace();
  230. // }
  231. // catch (NoSuchAlgorithmException e)
  232. // {
  233. // // TODO Auto-generated catch block
  234. // e.printStackTrace();
  235. // }
  236. // catch (CertificateException e)
  237. // {
  238. // // TODO Auto-generated catch block
  239. // e.printStackTrace();
  240. // }
  241. // catch (IOException e)
  242. // {
  243. // // TODO Auto-generated catch block
  244. // e.printStackTrace();
  245. // }
  246. // catch (KeyManagementException e)
  247. // {
  248. // // TODO Auto-generated catch block
  249. // e.printStackTrace();
  250. // }
  251. // catch (UnrecoverableKeyException e)
  252. // {
  253. // // TODO Auto-generated catch block
  254. // e.printStackTrace();
  255. // }
  256. //
  257. // }
  258. public static String getJson(String url, Bundle parms)
  259. {
  260. String TAG = "net_dbg@GetJson";
  261. Log.d(TAG, "entry");
  262. // if (true)
  263. // return fakegetJson(url);
  264. try
  265. {
  266. // BasicHttpParams httpParams = new BasicHttpParams();
  267. // HttpConnectionParams.setConnectionTimeout(httpParams,
  268. // REQUEST_TIMEOUT);
  269. // HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
  270. HttpClient client = getNewHttpClient();// new
  271. // DefaultHttpClient(httpParams);
  272. HttpPost post = new HttpPost(url);
  273. MultipartEntity reqEntity = new MultipartEntity(
  274. HttpMultipartMode.BROWSER_COMPATIBLE);
  275. Set<String> keys = parms.keySet();
  276. for (String key : keys)
  277. {
  278. if (key.contains("_file"))
  279. {
  280. ;
  281. }
  282. else
  283. reqEntity.addPart(key, new StringBody(parms.get(key)
  284. .toString()));
  285. }
  286. post.setEntity(reqEntity);
  287. HttpResponse response = client.execute(post);
  288. int statucode = response.getStatusLine().getStatusCode();
  289. if (statucode == HttpStatus.SC_OK)
  290. {
  291. HttpEntity resEntity = response.getEntity();
  292. if (resEntity != null)
  293. {
  294. Log.d(TAG,
  295. "Response: content len==>"
  296. + resEntity.getContentLength());
  297. InputStream is = resEntity.getContent();
  298. try
  299. {
  300. BufferedReader br = new BufferedReader(
  301. new InputStreamReader(is, "utf-8"), 8);
  302. StringBuilder sb = new StringBuilder();
  303. String line = null;
  304. while ((line = br.readLine()) != null)
  305. {
  306. sb.append(line + "\n");
  307. }
  308. Log.d(TAG, "Response: content begin");
  309. Log.d(TAG, sb.toString());
  310. Log.d(TAG, "Response: content end");
  311. if (sb.length() <= 0)
  312. {
  313. return null;
  314. }
  315. return sb.toString();
  316. // JSONObject obj = new JSONObject(sb.toString());
  317. // if (obj.length() > 0)
  318. // {
  319. // // JSONObject obj = array.getJSONObject(0);
  320. // try
  321. // {
  322. // int verifyresult = Integer.parseInt(obj
  323. // .getString("result"));
  324. // if (verifyresult == Network.AP_USER_AUTH)
  325. // {
  326. // return RESULT_TRUE;
  327. // }
  328. // else
  329. // {
  330. // return RESULT_FALSE;
  331. // }
  332. // }
  333. // catch (Exception e)
  334. // {
  335. // Log.e(TAG, e.toString());
  336. // return RESULT_ERROR;
  337. // }
  338. // }
  339. }
  340. catch (Exception e)
  341. {
  342. Log.e(TAG, e.toString());
  343. return null;
  344. // TODO: handle exception
  345. }
  346. finally
  347. {
  348. is.close();
  349. }
  350. }
  351. else
  352. {
  353. /*
  354. * resEntity is null
  355. */
  356. Log.d(TAG, "RESPONSE ENTITY IS NULL");
  357. return null;
  358. }
  359. }
  360. else
  361. {
  362. /*
  363. * Http error; out put error code;
  364. */
  365. Log.d(TAG, "HTTP " + statucode);
  366. HttpEntity resEntity = response.getEntity();
  367. if (resEntity != null)
  368. {
  369. InputStream is = resEntity.getContent();
  370. try
  371. {
  372. BufferedReader br = new BufferedReader(
  373. new InputStreamReader(is, "utf-8"), 8);
  374. StringBuilder sb = new StringBuilder();
  375. String line = null;
  376. while ((line = br.readLine()) != null)
  377. {
  378. sb.append(line + "\n");
  379. }
  380. Log.d(TAG, "Response: content begin");
  381. Log.d(TAG, sb.toString());
  382. Log.d(TAG, "Response: content end");
  383. return null;
  384. }
  385. catch (Exception e)
  386. {
  387. Log.e(TAG, e.toString());
  388. return null;
  389. // TODO: handle exception
  390. }
  391. finally
  392. {
  393. is.close();
  394. }
  395. }
  396. else
  397. {
  398. /*
  399. * resEntity is null
  400. */
  401. Log.e(TAG, "RESPONSE ENTITY IS NULL");
  402. return null;
  403. }
  404. }
  405. }
  406. catch (ConnectTimeoutException e)
  407. {
  408. Log.d(TAG, "request time out");
  409. return null;
  410. }
  411. catch (Exception e)
  412. {
  413. Log.d(TAG, e.toString());
  414. return null;
  415. }
  416. }
  417. // public static int VerifyUser(String user, String password)
  418. // {
  419. // String TAG = "net_dbg@VerifyUser";
  420. // Log.d(TAG, "entry");
  421. // try
  422. // {
  423. // BasicHttpParams httpParams = new BasicHttpParams();
  424. // HttpConnectionParams.setConnectionTimeout(httpParams,
  425. // REQUEST_TIMEOUT);
  426. // HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
  427. // HttpClient client = new DefaultHttpClient(httpParams);
  428. // HttpPost post = new HttpPost(URL_VERIFY_USER);
  429. // MultipartEntity reqEntity = new MultipartEntity(
  430. // HttpMultipartMode.BROWSER_COMPATIBLE);
  431. // reqEntity.addPart("user", new StringBody(user));
  432. // reqEntity.addPart("password", new StringBody(password));
  433. //
  434. // post.setEntity(reqEntity);
  435. // HttpResponse response = client.execute(post);
  436. // int statucode = response.getStatusLine().getStatusCode();
  437. // if (statucode == HttpStatus.SC_OK)
  438. // {
  439. // HttpEntity resEntity = response.getEntity();
  440. // if (resEntity != null)
  441. // {
  442. // Log.d(TAG,
  443. // "Response: content len==>"
  444. // + resEntity.getContentLength());
  445. // InputStream is = resEntity.getContent();
  446. // try
  447. // {
  448. //
  449. // BufferedReader br = new BufferedReader(
  450. // new InputStreamReader(is, "utf-8"), 8);
  451. // StringBuilder sb = new StringBuilder();
  452. // String line = null;
  453. // while ((line = br.readLine()) != null)
  454. // {
  455. // sb.append(line + "\n");
  456. // }
  457. //
  458. // Log.d(TAG, "Response: content begin");
  459. // Log.d(TAG, sb.toString());
  460. // Log.d(TAG, "Response: content end");
  461. //
  462. // if (sb.length() <= 0)
  463. // {
  464. //
  465. // return RESULT_NET_ERROR;
  466. // }
  467. // JSONObject obj = new JSONObject(sb.toString());
  468. // if (obj.length() > 0)
  469. // {
  470. // // JSONObject obj = array.getJSONObject(0);
  471. // try
  472. // {
  473. // int verifyresult = Integer.parseInt(obj
  474. // .getString("result"));
  475. // if (verifyresult == Network.AP_USER_AUTH)
  476. // {
  477. // return RESULT_TRUE;
  478. // }
  479. // else
  480. // {
  481. // return RESULT_FALSE;
  482. // }
  483. // }
  484. // catch (Exception e)
  485. // {
  486. // Log.e(TAG, e.toString());
  487. // return RESULT_ERROR;
  488. // }
  489. // }
  490. // }
  491. // catch (Exception e)
  492. // {
  493. // Log.e(TAG, e.toString());
  494. // return RESULT_ERROR;
  495. // // TODO: handle exception
  496. // }
  497. // finally
  498. // {
  499. // is.close();
  500. //
  501. // }
  502. //
  503. // }
  504. // else
  505. // {
  506. // /*
  507. // * resEntity is null
  508. // */
  509. // Log.d(TAG, "RESPONSE ENTITY IS NULL");
  510. // return RESULT_NET_ERROR;
  511. // }
  512. //
  513. // }
  514. // else
  515. // {
  516. // /*
  517. // * Http error; out put error code;
  518. // */
  519. // Log.d(TAG, "HTTP " + statucode);
  520. //
  521. // HttpEntity resEntity = response.getEntity();
  522. // if (resEntity != null)
  523. // {
  524. //
  525. // InputStream is = resEntity.getContent();
  526. // try
  527. // {
  528. //
  529. // BufferedReader br = new BufferedReader(
  530. // new InputStreamReader(is, "utf-8"), 8);
  531. // StringBuilder sb = new StringBuilder();
  532. // String line = null;
  533. // while ((line = br.readLine()) != null)
  534. // {
  535. // sb.append(line + "\n");
  536. // }
  537. //
  538. // Log.d(TAG, "Response: content begin");
  539. // Log.d(TAG, sb.toString());
  540. // Log.d(TAG, "Response: content end");
  541. // return RESULT_ERROR;
  542. // }
  543. // catch (Exception e)
  544. // {
  545. // Log.e(TAG, e.toString());
  546. // return RESULT_ERROR;
  547. // // TODO: handle exception
  548. // }
  549. // finally
  550. // {
  551. // is.close();
  552. //
  553. // }
  554. //
  555. // }
  556. // else
  557. // {
  558. // /*
  559. // * resEntity is null
  560. // */
  561. // Log.e(TAG, "RESPONSE ENTITY IS NULL");
  562. // return RESULT_NET_ERROR;
  563. // }
  564. // }
  565. //
  566. // }
  567. // catch (ConnectTimeoutException e)
  568. // {
  569. // Log.d(TAG, "request time out");
  570. // return RESULT_NET_ERROR;
  571. //
  572. // }
  573. // catch (Exception e)
  574. // {
  575. // Log.d(TAG, e.toString());
  576. // return RESULT_ERROR;
  577. // }
  578. // return RESULT_ERROR;
  579. // }
  580. // public static int UploadFile(String path, String user, String password,
  581. // String pid)
  582. // {
  583. // String TAG = "net_dbg@VerifyUser";
  584. // Log.d(TAG, "entry");
  585. //
  586. // Log.d(TAG, "sourcefile:" + path);
  587. // File file = new File(path);
  588. //
  589. // if (file.exists() == false)
  590. // return RESULT_LOCALFILE_ERROR;
  591. //
  592. // try
  593. // {
  594. // BasicHttpParams httpParams = new BasicHttpParams();
  595. // HttpConnectionParams.setConnectionTimeout(httpParams,
  596. // REQUEST_TIMEOUT);
  597. // HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
  598. // HttpClient client = new DefaultHttpClient(httpParams);
  599. // HttpPost post = new HttpPost(URL_UPLOAD_PHOTO);
  600. // MultipartEntity reqEntity = new MultipartEntity(
  601. // HttpMultipartMode.BROWSER_COMPATIBLE);
  602. // reqEntity.addPart("user", new StringBody(user));
  603. // reqEntity.addPart("password", new StringBody(password));
  604. // reqEntity.addPart("pid", new StringBody(pid));
  605. // FileBody bin = new FileBody(file);
  606. // reqEntity.addPart("imagefile", bin);
  607. // post.setEntity(reqEntity);
  608. // HttpResponse response = client.execute(post);
  609. // int statucode = response.getStatusLine().getStatusCode();
  610. // if (statucode == HttpStatus.SC_OK)
  611. // {
  612. // HttpEntity resEntity = response.getEntity();
  613. // if (resEntity != null)
  614. // {
  615. // Log.d(TAG,
  616. // "Response: content len==>"
  617. // + resEntity.getContentLength());
  618. // InputStream is = resEntity.getContent();
  619. // try
  620. // {
  621. //
  622. // BufferedReader br = new BufferedReader(
  623. // new InputStreamReader(is, "utf-8"), 8);
  624. // StringBuilder sb = new StringBuilder();
  625. // String line = null;
  626. // while ((line = br.readLine()) != null)
  627. // {
  628. // sb.append(line + "\n");
  629. // }
  630. //
  631. // Log.d(TAG, "Response: content begin");
  632. // Log.d(TAG, sb.toString());
  633. // Log.d(TAG, "Response: content end");
  634. //
  635. // if (sb.length() <= 0)
  636. // {
  637. //
  638. // return RESULT_NET_ERROR;
  639. // }
  640. // JSONObject obj = new JSONObject(sb.toString());
  641. // if (obj.length() > 0)
  642. // {
  643. // // JSONObject obj = array.getJSONObject(0);
  644. // try
  645. // {
  646. // int uploadresult = Integer.parseInt(obj
  647. // .getString("result"));
  648. // if (uploadresult == Network.AP_UPLOAD_SUCCESS)
  649. // {
  650. // return RESULT_TRUE;
  651. // }
  652. // else
  653. // if (uploadresult == Network.AP_USER_NOT_AUTH)
  654. // {
  655. // Log.d(TAG, "RESULT_ERR_USERAUTH");
  656. // return RESULT_USERAUTH_ERROR;
  657. // }
  658. // else
  659. // {
  660. // return RESULT_FALSE;
  661. // }
  662. // }
  663. // catch (Exception e)
  664. // {
  665. // Log.e(TAG, e.toString());
  666. // return RESULT_FALSE;
  667. // }
  668. // }
  669. // }
  670. // catch (Exception e)
  671. // {
  672. // Log.e(TAG, e.toString());
  673. // return RESULT_ERROR;
  674. // // TODO: handle exception
  675. // }
  676. // finally
  677. // {
  678. // is.close();
  679. //
  680. // }
  681. //
  682. // }
  683. // else
  684. // {
  685. // /*
  686. // * resEntity is null
  687. // */
  688. // Log.d(TAG, "RESPONSE ENTITY IS NULL");
  689. // return RESULT_NET_ERROR;
  690. // }
  691. //
  692. // }
  693. // else
  694. // {
  695. // /*
  696. // * Http error; out put error code;
  697. // */
  698. // Log.d(TAG, "HTTP " + statucode);
  699. //
  700. // HttpEntity resEntity = response.getEntity();
  701. // if (resEntity != null)
  702. // {
  703. //
  704. // InputStream is = resEntity.getContent();
  705. // try
  706. // {
  707. //
  708. // BufferedReader br = new BufferedReader(
  709. // new InputStreamReader(is, "utf-8"), 8);
  710. // StringBuilder sb = new StringBuilder();
  711. // String line = null;
  712. // while ((line = br.readLine()) != null)
  713. // {
  714. // sb.append(line + "\n");
  715. // }
  716. //
  717. // Log.d(TAG, "Response: content begin");
  718. // Log.d(TAG, sb.toString());
  719. // Log.d(TAG, "Response: content end");
  720. // return RESULT_ERROR;
  721. // }
  722. // catch (Exception e)
  723. // {
  724. // Log.e(TAG, e.toString());
  725. // return RESULT_ERROR;
  726. // // TODO: handle exception
  727. // }
  728. // finally
  729. // {
  730. // is.close();
  731. //
  732. // }
  733. //
  734. // }
  735. // else
  736. // {
  737. // /*
  738. // * resEntity is null
  739. // */
  740. // Log.e(TAG, "RESPONSE ENTITY IS NULL");
  741. // return RESULT_NET_ERROR;
  742. // }
  743. // }
  744. //
  745. // }
  746. // catch (ConnectTimeoutException e)
  747. // {
  748. // Log.d(TAG, "request time out");
  749. // return RESULT_NET_ERROR;
  750. //
  751. // }
  752. // catch (Exception e)
  753. // {
  754. // Log.d(TAG, e.toString());
  755. // return RESULT_ERROR;
  756. // }
  757. //
  758. // return RESULT_FALSE;
  759. //
  760. // // try
  761. // // {
  762. // // HttpClient client = new DefaultHttpClient();
  763. // // HttpPost post = new HttpPost(url);
  764. // // MultipartEntity reqEntity = new MultipartEntity(
  765. // // HttpMultipartMode.BROWSER_COMPATIBLE);
  766. // // reqEntity.addPart("user", new StringBody(user));
  767. // // reqEntity.addPart("password", new StringBody(password));
  768. // // reqEntity.addPart("pid", new StringBody(pid));
  769. // // FileBody bin = new FileBody(file);
  770. // // reqEntity.addPart("imagefile", bin);
  771. // // post.setEntity(reqEntity);
  772. // // HttpResponse response = client.execute(post);
  773. // // HttpEntity resEntity = response.getEntity();
  774. // // if (resEntity != null)
  775. // // {
  776. // //
  777. // // String result = EntityUtils.toString(resEntity);
  778. // // Log.d(TAG, "Response:" + result);
  779. // // return Integer.parseInt(result);
  780. // // // if(Boolean.parseBoolean(result)==true)
  781. // // // return true;
  782. // // // else
  783. // // // return false;
  784. // // }
  785. // //
  786. // // }
  787. // // catch (Exception e)
  788. // // {
  789. // // e.printStackTrace();
  790. // // }
  791. // // return 0;
  792. // }
  793. public static int get_recordcount(String name, String password, Bundle parms)
  794. {
  795. String TAG = "net_dbg@get_recordcount";
  796. // parms.putString("user", name);
  797. // parms.putString("password", password);
  798. // if (!Network.NetworkIsAvailable())
  799. // {
  800. // Log.d(TAG, "network not available!");
  801. // return Network.RESULT_NET_NOTAVAILABLE; // network not available
  802. // }
  803. parms.putString("action", "handset_search_count");
  804. parms.putString("sessionid", ApexTrackingApplication.get_sessionid());
  805. String jstr = getJson(Network.URL_REQUEST_COUNT, parms);
  806. if (jstr == null || jstr.length() <= 0)
  807. {
  808. Log.d(TAG, "json is wrong");
  809. return Network.RESULT_NET_ERROR;
  810. }
  811. JSONObject jsobj;
  812. // array = new JSONArray(json);
  813. try
  814. {
  815. jsobj = new JSONObject(jstr);
  816. if (jsobj.length() > 0)
  817. {
  818. if (jsobj.getInt("result") != Network.AP_USER_AUTH)
  819. {
  820. // session expired
  821. Log.d(TAG,
  822. "USER NOT AUTHORIZED CODE="
  823. + jsobj.getInt("result"));
  824. return RESULT_SESSION_EXPIRED;
  825. // if (get_Auth(name, password) == RESULT_TRUE)
  826. // {
  827. // return get_recordcount(name, password, parms);
  828. //
  829. // }
  830. // else
  831. // {
  832. //
  833. // Log.d(TAG,
  834. // "USER NOT AUTHORIZED CODE="
  835. // + jsobj.getInt("result"));
  836. // return RESULT_SESSION_EXPIRED;
  837. // }
  838. }
  839. else
  840. {
  841. return jsobj.getInt("count");
  842. }
  843. }
  844. else
  845. {
  846. Log.d(TAG, "json is wrong");
  847. return Network.RESULT_NET_ERROR;
  848. }
  849. }
  850. catch (JSONException e)
  851. {
  852. // TODO Auto-generated catch block
  853. e.printStackTrace();
  854. }
  855. return RESULT_ERROR;
  856. }
  857. public static String get_records(String name, String password, Bundle parms)
  858. {
  859. String TAG = "net_dbg@get_records";
  860. // parms.putString("user", name);
  861. // parms.putString("password", password);
  862. // if (!Network.NetworkIsAvailable())
  863. // {
  864. // Log.d(TAG, "network not available!");
  865. // return "Network.RESULT_NET_NOTAVAILABLE"; // network not available
  866. // }
  867. parms.putString("action", "handset_search");
  868. parms.putString("sessionid", ApexTrackingApplication.get_sessionid());
  869. String jstr = getJson(Network.URL_REQUEST_RECORDS, parms);
  870. if (jstr == null || jstr.length() <= 0)
  871. {
  872. Log.d(TAG, "json is wrong");
  873. return null;
  874. }
  875. JSONObject jsobj;
  876. //
  877. // array = new JSONArray(json);
  878. try
  879. {
  880. jsobj = new JSONObject(jstr);
  881. if (jsobj.length() > 0)
  882. {
  883. if (jsobj.getInt("result") != Network.AP_USER_AUTH)
  884. {
  885. // session expired
  886. if (get_Auth(name, password) == RESULT_TRUE)
  887. {
  888. return get_records(name, password, parms);
  889. }
  890. else
  891. {
  892. Log.d(TAG,
  893. "USER NOT AUTHORIZED CODE="
  894. + jsobj.getInt("result"));
  895. return null;
  896. }
  897. }
  898. else
  899. {
  900. return jstr;
  901. }
  902. }
  903. else
  904. {
  905. Log.d(TAG, "json is wrong");
  906. return null;
  907. }
  908. }
  909. catch (JSONException e)
  910. {
  911. // TODO Auto-generated catch block
  912. e.printStackTrace();
  913. }
  914. return null;
  915. // return RESULT_ERROR;
  916. }
  917. public static int get_Auth(String name, String password)
  918. {
  919. String TAG = "net_dbg@get_Auth";
  920. Log.d(TAG, "u:" + name + ";p:" + password);
  921. if (!Network.NetworkIsAvailable())
  922. {
  923. Log.d(TAG, "network not available!");
  924. return Network.RESULT_NET_NOTAVAILABLE; // network not available
  925. }
  926. Bundle parms = new Bundle();
  927. parms.putString("user", name);
  928. parms.putString("password", password);
  929. parms.putString("action", "handset_login");
  930. int ver = ApexTrackingApplication.get_instance()
  931. .getSharedPreferences("Apex_auth", Context.MODE_PRIVATE)
  932. .getInt("AuthInfoVer", 0);
  933. parms.putString("auth_ver", ver + "");
  934. String jstr = getJson(Network.URL_UPDATE_AUTH, parms);
  935. /*
  936. * error occur while get authorization info from server. include can not
  937. * reach server , wrong parms ,server get wrong , etc.
  938. */
  939. if (jstr == null || jstr.length() <= 0)
  940. {
  941. Log.d(TAG, "json is wrong");
  942. return Network.RESULT_NET_ERROR;
  943. }
  944. return parse_authinfo(jstr, name);
  945. }
  946. private static int parse_authinfo(String json, String user)
  947. {
  948. String TAG = "net_dbg@parse_authinfo";
  949. Log.d(TAG, json);
  950. // JSONArray array;
  951. JSONObject jsobj;
  952. SQLiteDatabase db = null;
  953. try
  954. {
  955. // array = new JSONArray(json);
  956. jsobj = new JSONObject(json);
  957. if (jsobj.length() > 0)
  958. {
  959. // JSONObject objresult = jsobj.get.getJSONObject(0);// result
  960. // the
  961. // server result
  962. // ;
  963. if (jsobj.getInt("result") != Network.AP_USER_AUTH)
  964. {
  965. // user not authorized return
  966. Log.d(TAG,
  967. "USER NOT AUTHORIZED CODE="
  968. + jsobj.getInt("result"));
  969. return RESULT_FALSE;
  970. }
  971. JSONObject objheader = jsobj.getJSONObject("header");
  972. // JSONObject objsessionid = jsobj.getJSONObject(1); // session
  973. // id
  974. // on
  975. // server;
  976. ApexTrackingApplication.put_sessionid(objheader
  977. .getString("sessionid"));
  978. Log.d(TAG, "sessionid=" + objheader.getString("sessionid"));
  979. // JSONObject objupdate = array.getJSONObject(3); // whether
  980. // need
  981. // update ;
  982. if (objheader.getBoolean("update") == false)
  983. {
  984. // no update on the server;
  985. return RESULT_TRUE;
  986. }
  987. // JSONObject objver = array.getJSONObject(4); // new version
  988. // get
  989. // from server;
  990. Editor editor = ApexTrackingApplication
  991. .get_instance()
  992. .getSharedPreferences("Apex_auth", Context.MODE_PRIVATE)
  993. .edit();
  994. editor.putInt("AuthInfoVer", objheader.getInt("ver"));
  995. JSONObject objfuncs = jsobj.getJSONObject("functions");
  996. Iterator it = objfuncs.keys();
  997. db = dbUtil.OpenDB(ApexTrackingApplication.get_instance(),
  998. null, true);
  999. String sql = "insert into fields_info(name,aname,field_type,function_name,behavior,priority,show,user) values(?,?,?,?,?,?,?,?)";
  1000. db.execSQL("update fields_info set abandon = 1 where user ='"
  1001. + user + "'");
  1002. SQLiteStatement stat = db.compileStatement(sql);
  1003. db.beginTransaction();
  1004. String field_name, field_type, alias_name;
  1005. while (it.hasNext()) // loop for each function
  1006. {
  1007. String func_name = (String) it.next();
  1008. // Set<String> funset = new HashSet<String>();
  1009. JSONObject objfun = objfuncs.getJSONObject(func_name);
  1010. int behavior, priority = 999;
  1011. int show = 1;
  1012. JSONObject objbehavior = objfun.getJSONObject("search");
  1013. Iterator itbehavior = objbehavior.keys();
  1014. behavior = BEHAVIOR_SEARCH;
  1015. while (itbehavior.hasNext()) // loop for search fields in
  1016. // certain function
  1017. {
  1018. String field = (String) itbehavior.next();
  1019. JSONObject field_info = objbehavior
  1020. .getJSONObject(field);
  1021. field_name = field_info.getString("name");
  1022. field_type = field_info.getString("type");
  1023. alias_name = field_info.getString("alias");
  1024. int id = dbUtil.get_recordid(db, "fields_info",
  1025. "name='" + field_name + "' and behavior="
  1026. + behavior + " and function_name='"
  1027. + func_name + "' and user='" + user
  1028. + "'");
  1029. if (id >= 0) // record exist;
  1030. {
  1031. db.execSQL("update fields_info set abandon = 0 where _id ="
  1032. + id);
  1033. }
  1034. else
  1035. {
  1036. stat.bindString(1, field_name);
  1037. stat.bindString(2, alias_name);
  1038. stat.bindString(3, field_type);
  1039. stat.bindString(4, func_name);
  1040. stat.bindLong(5, behavior);
  1041. stat.bindLong(6, priority);
  1042. stat.bindLong(7, show);
  1043. stat.bindString(8, user);
  1044. stat.executeInsert();
  1045. }
  1046. }
  1047. objbehavior = objfun.getJSONObject("result");
  1048. Iterator itresult = objbehavior.keys();
  1049. behavior = BEHAVIOR_RESULT;
  1050. while (itresult.hasNext()) // loop for result fields in
  1051. // certain function
  1052. {
  1053. String field = (String) itresult.next();
  1054. JSONObject field_info = objbehavior
  1055. .getJSONObject(field);
  1056. field_name = field_info.getString("name");
  1057. field_type = field_info.getString("type");
  1058. alias_name = field_info.getString("alias");
  1059. int id = dbUtil.get_recordid(db, "fields_info",
  1060. "name='" + field_name + "' and behavior="
  1061. + behavior + " and function_name='"
  1062. + func_name + "' and user='" + user
  1063. + "'");
  1064. if (id >= 0) // record exist;
  1065. {
  1066. db.execSQL("update fields_info set abandon = 0 where _id ="
  1067. + id);
  1068. }
  1069. else
  1070. {
  1071. stat.bindString(1, field_name);
  1072. stat.bindString(2, alias_name);
  1073. stat.bindString(3, field_type);
  1074. stat.bindString(4, func_name);
  1075. stat.bindLong(5, behavior);
  1076. stat.bindLong(6, priority);
  1077. stat.bindLong(7, show);
  1078. stat.bindString(8, user);
  1079. stat.executeInsert();
  1080. }
  1081. }
  1082. // editor.putString(func_name, objfun.toString());
  1083. // JSONArray arrfun = jsobj.get(i);
  1084. // JSONObject objname = arrfun.getJSONObject(0);
  1085. //
  1086. // funset.add(objfun.getString("name"));
  1087. // funset.add(objfun.getJSONObject("search").toString());
  1088. // funset.add(objfun.getJSONObject("result").toString());
  1089. // editor.putStringSet(objfun.getString("name"), funset);
  1090. // String value = obj.getString(key);
  1091. // JSONArray array = obj.getJSONArray(key);
  1092. // for (int i = 0; i < array.length(); i++)
  1093. // {
  1094. // JSONObject jsonobject = array.getJSONObject(i);
  1095. // jsonobject.put("name", key);
  1096. // jsonobject.put("exp",
  1097. // key + "=" + jsonobject.getString("value"));
  1098. // newArray.put(jsonobject);
  1099. // }
  1100. }
  1101. db.execSQL("delete from fields_info where abandon = 1");
  1102. db.setTransactionSuccessful();
  1103. db.endTransaction();
  1104. editor.commit();
  1105. return RESULT_TRUE;
  1106. }
  1107. Log.d(TAG, "json is wrong");
  1108. return RESULT_USERAUTH_ERROR;
  1109. }
  1110. catch (JSONException e1)
  1111. {
  1112. // TODO Auto-generated catch block
  1113. e1.printStackTrace();
  1114. Log.d(TAG, "json is wrong");
  1115. }
  1116. finally
  1117. {
  1118. dbUtil.CloseDB(db);
  1119. }
  1120. // try
  1121. // {
  1122. // m_RemoteVerCode = Integer
  1123. // .parseInt(obj.getString("verCode"));
  1124. // m_RemoteVerName = obj.getString("verName");
  1125. // m_NewVerUrl = obj.getString("URL");
  1126. // }
  1127. // catch (Exception e)
  1128. // {
  1129. // m_RemoteVerCode = -1;
  1130. // m_RemoteVerName = "";
  1131. // m_NewVerUrl = "";
  1132. // dbgUtil.Log(Log.INFO,TAG, "download failed json file wrong!");
  1133. // return false;
  1134. // }
  1135. Log.d(TAG, "json is wrong");
  1136. return RESULT_USERAUTH_ERROR;
  1137. }
  1138. // private void writeData(JSONObject allData)
  1139. // {
  1140. //
  1141. // File file = new File(Environment.getExternalStorageDirectory()
  1142. // .toString() + File.separator + "live.txt");
  1143. // if (!file.exists())
  1144. // {
  1145. // try
  1146. // {
  1147. // file.createNewFile();
  1148. // }
  1149. // catch (IOException e)
  1150. // {
  1151. // e.printStackTrace();
  1152. // }
  1153. // }
  1154. // FileOutputStream fos;
  1155. // OutputStreamWriter osw = null;
  1156. // try
  1157. // {
  1158. // fos = new FileOutputStream(file);
  1159. //
  1160. // osw = new OutputStreamWriter(fos, "UTF-8");
  1161. // osw.write(allData.toString());
  1162. // osw.flush();
  1163. // }
  1164. // catch (FileNotFoundException e)
  1165. // {
  1166. // e.printStackTrace();
  1167. // }
  1168. // catch (UnsupportedEncodingException e)
  1169. // {
  1170. // e.printStackTrace();
  1171. // }
  1172. // catch (IOException e)
  1173. // {
  1174. // e.printStackTrace();
  1175. // }
  1176. // finally
  1177. // {
  1178. // if (osw != null)
  1179. // {
  1180. // try
  1181. // {
  1182. // osw.close();
  1183. // }
  1184. // catch (IOException e)
  1185. // {
  1186. // e.printStackTrace();
  1187. // }
  1188. // }
  1189. // }
  1190. // }
  1191. public static boolean NetworkIsAvailable()// Context context)
  1192. {
  1193. String TAG = "net_dbg@CheckNetwork";
  1194. ConnectivityManager connManager = (ConnectivityManager) ApexTrackingApplication
  1195. .get_instance().getSystemService(Context.CONNECTIVITY_SERVICE);
  1196. // .getSystemService(Context.CONNECTIVITY_SERVICE);
  1197. NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
  1198. if (networkInfo == null)
  1199. {
  1200. Log.d(TAG, "can not get Active NetworkInfo!");
  1201. // dbgUtil.Log(Log.DEBUG, "Current Network info",
  1202. // "can not get Active NetworkInfo!");
  1203. return false;
  1204. }
  1205. NetworkInfo.State netState = networkInfo.getState();
  1206. if (netState != NetworkInfo.State.CONNECTED)
  1207. {
  1208. Log.d(TAG, "not Connected!State=" + netState);
  1209. // dbgUtil.Log(Log.DEBUG, "Current Network info",
  1210. // "not Connected!State=" + netState);
  1211. return false;
  1212. }
  1213. // int iconntype = -1;
  1214. // iconntype = networkInfo.getType();
  1215. // boolean bUseMobileNetwork = context.getSharedPreferences(
  1216. // "PhoneAsstPref", 0).getBoolean("UseMobileNetwork", false);
  1217. //
  1218. // if (bUseMobileNetwork == false
  1219. // && iconntype != ConnectivityManager.TYPE_WIFI && iconntype != 9/*
  1220. // earthnet */)
  1221. // {
  1222. // Log.d(TAG,);
  1223. // dbgUtil.Log(Log.DEBUG, "Current Network info",
  1224. // "not allowed!Connection type=" + networkInfo.getTypeName());
  1225. // return false;
  1226. // }
  1227. boolean bavailable = networkInfo.isAvailable();
  1228. String strtype = networkInfo.getTypeName();
  1229. Log.d(TAG, " type = " + strtype + " abailable = " + bavailable
  1230. + " state " + netState);
  1231. // dbgUtil.Log(Log.INFO, "Current Network info", " type = " + strtype
  1232. // + " abailable = " + bavailable + " state " + netState);
  1233. return bavailable;
  1234. }
  1235. public static class SSLSocketFactoryEx extends SSLSocketFactory
  1236. {
  1237. SSLContext sslContext = SSLContext.getInstance("TLS");
  1238. public SSLSocketFactoryEx(KeyStore truststore)
  1239. throws NoSuchAlgorithmException, KeyManagementException,
  1240. KeyStoreException, UnrecoverableKeyException
  1241. {
  1242. super(truststore);
  1243. TrustManager tm = new X509TrustManager()
  1244. {
  1245. public java.security.cert.X509Certificate[] getAcceptedIssuers()
  1246. {
  1247. return null;
  1248. }
  1249. @Override
  1250. public void checkClientTrusted(
  1251. java.security.cert.X509Certificate[] chain,
  1252. String authType)
  1253. throws java.security.cert.CertificateException
  1254. {
  1255. }
  1256. @Override
  1257. public void checkServerTrusted(
  1258. java.security.cert.X509Certificate[] chain,
  1259. String authType)
  1260. throws java.security.cert.CertificateException
  1261. {
  1262. }
  1263. };
  1264. sslContext.init(null, new TrustManager[] { tm }, null);
  1265. }
  1266. @Override
  1267. public Socket createSocket(Socket socket, String host, int port,
  1268. boolean autoClose) throws IOException, UnknownHostException
  1269. {
  1270. return sslContext.getSocketFactory().createSocket(socket, host,
  1271. port, autoClose);
  1272. }
  1273. @Override
  1274. public Socket createSocket() throws IOException
  1275. {
  1276. return sslContext.getSocketFactory().createSocket();
  1277. }
  1278. }
  1279. }