Android Http请求

悠悠 2022-06-17 12:28 247阅读 0赞

Android HTTP请求封装代码

复制代码

  1. /**
  2. * This class is the Utils of other classes.
  3. */
  4. public class HttpUtil {
  5. /** 变量/常量说明 */
  6. private static final String TAG = "HttpUtils";
  7. /** 超时时间 */
  8. private static int mTimeOut = 20000;
  9. /** 私钥密码 */
  10. /** 使用协议 */
  11. private static final String CLIENT_AGREEMENT = "TLS";
  12. /** 密钥管理器 */
  13. /** 变量/常量说明 */
  14. private static HttpUtil mHttpUtils = null;
  15. /**
  16. * 获取HPPS对象实例
  17. *
  18. * @param application
  19. * @return
  20. * @since V1.0
  21. */
  22. public static HttpUtil getInstace(Context context) {
  23. if (mHttpUtils == null) {
  24. mHttpUtils = new HttpUtil(context);
  25. }
  26. return mHttpUtils;
  27. }
  28. /**
  29. * @param application
  30. */
  31. private HttpUtil(Context context) {
  32. }
  33. /**
  34. * 这里对方法做描述
  35. *
  36. * @param servAddr
  37. * @param xmlBody
  38. * @return
  39. * @throws HttpException
  40. * @since V1.0
  41. */
  42. public String httpGetRequest(String servAddr) throws HttpException {
  43. // create connection
  44. String response = null;
  45. HttpURLConnection conn = null;
  46. boolean ret = false;
  47. InputStream in = null;
  48. try {
  49. URL url = new URL(servAddr);
  50. conn = (HttpURLConnection) url.openConnection();
  51. conn.setConnectTimeout(mTimeOut);
  52. conn.setReadTimeout(mTimeOut);
  53. conn.setDoInput(true);
  54. conn.setRequestMethod("GET");
  55. conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");
  56. if (conn.getResponseCode() == 200) {
  57. // getCookie(conn);
  58. in = new BufferedInputStream(conn.getInputStream());
  59. } else {
  60. in = new BufferedInputStream(conn.getErrorStream());
  61. }
  62. response = inputStream2String(in);
  63. in.close();
  64. in = null;
  65. ret = true;
  66. } catch (MalformedURLException e) {
  67. ret = false;
  68. e.printStackTrace();
  69. } catch (ProtocolException e) {
  70. ret = false;
  71. e.printStackTrace();
  72. } catch (IOException e) {
  73. ret = false;
  74. e.printStackTrace();
  75. } finally {
  76. if (in != null) {
  77. try {
  78. in.close();
  79. } catch (IOException e) {
  80. // TODO Auto-generated catch block
  81. e.printStackTrace();
  82. }
  83. in = null;
  84. }
  85. if (conn != null) {
  86. // 断开连接
  87. conn.disconnect();
  88. conn = null;
  89. }
  90. }
  91. // 抛出异常
  92. if (!ret) {
  93. throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
  94. }
  95. return response;
  96. }
  97. /**
  98. * 这里对方法做描述
  99. *
  100. * @return
  101. * @throws InvalidFormatException
  102. * @see
  103. * @since V1.0
  104. */
  105. public static String httpPostRequest(String path) {
  106. // create connection
  107. String response = null;
  108. HttpURLConnection conn = null;
  109. try {
  110. URL url = new URL(path);
  111. conn = (HttpURLConnection) url.openConnection();
  112. conn.setConnectTimeout(mTimeOut);
  113. conn.setDoInput(true);
  114. conn.setDoOutput(true);
  115. conn.setRequestMethod("POST");
  116. conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");
  117. InputStream in = new BufferedInputStream(conn.getInputStream());
  118. response = inputStream2String(in);
  119. } catch (MalformedURLException e) {
  120. e.printStackTrace();
  121. } catch (ProtocolException e) {
  122. e.printStackTrace();
  123. } catch (IOException e) {
  124. e.printStackTrace();
  125. } catch (Exception e) {
  126. e.printStackTrace();
  127. } finally {
  128. if (conn != null) {
  129. // 断开连接
  130. conn.disconnect();
  131. conn = null;
  132. }
  133. }
  134. return response;
  135. }
  136. /**
  137. * httpPost方式
  138. *
  139. * @param servAddr
  140. * @param xmlBody
  141. * @return
  142. * @throws HttpException
  143. * @since V1.0
  144. */
  145. public String httpPostRequest(String servAddr, String xmlBody) throws HttpException {
  146. // create connection
  147. String response = null;
  148. HttpURLConnection conn = null;
  149. boolean ret = false;
  150. InputStream in = null;
  151. DataOutputStream os = null;
  152. try {
  153. URL url = new URL(servAddr);
  154. conn = (HttpURLConnection) url.openConnection();
  155. conn.setConnectTimeout(mTimeOut);
  156. conn.setReadTimeout(mTimeOut);
  157. conn.setDoInput(true);
  158. conn.setDoOutput(true);
  159. conn.setRequestMethod("POST");
  160. conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");
  161. // send xml contant to server
  162. os = new DataOutputStream(conn.getOutputStream());
  163. os.write(xmlBody.getBytes(), 0, xmlBody.getBytes().length);
  164. os.flush();
  165. os.close();
  166. os = null;
  167. if (conn.getResponseCode() == 200) {
  168. // getCookie(conn);
  169. in = new BufferedInputStream(conn.getInputStream());
  170. } else {
  171. in = new BufferedInputStream(conn.getErrorStream());
  172. }
  173. response = inputStream2String(in);
  174. in.close();
  175. in = null;
  176. ret = true;
  177. } catch (MalformedURLException e) {
  178. ret = false;
  179. e.printStackTrace();
  180. } catch (ProtocolException e) {
  181. ret = false;
  182. e.printStackTrace();
  183. } catch (IOException e) {
  184. ret = false;
  185. e.printStackTrace();
  186. } finally {
  187. try {
  188. if (in != null) {
  189. in.close();
  190. }
  191. if (os != null) {
  192. os.close();
  193. }
  194. } catch (IOException e) {
  195. e.printStackTrace();
  196. }
  197. in = null;
  198. if (conn != null) {
  199. // 断开连接
  200. conn.disconnect();
  201. conn = null;
  202. }
  203. }
  204. // 抛出异常
  205. if (!ret) {
  206. throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
  207. }
  208. return response;
  209. }
  210. /**
  211. * 这里对方法做描述
  212. *
  213. * @return
  214. * @throws HttpException
  215. * @see
  216. * @since V1.0
  217. */
  218. public String httpsGetRequest(String servHttpsAddr) {
  219. if (servHttpsAddr == null || servHttpsAddr.equals("")) {
  220. CLog.d(TAG, "sslGetRequest servHttpsAddr == null");
  221. return "";
  222. }
  223. boolean bRet = verifyHttpsUrl(servHttpsAddr);
  224. if (!bRet) {
  225. CLog.d(TAG, "sslGetRequest verifyHttpsUrl fail");
  226. return "";
  227. }
  228. String response = "";
  229. try {
  230. response = getSslRequest(servHttpsAddr);
  231. } catch (HttpException e) {
  232. e.printStackTrace();
  233. CLog.d(TAG, "sslGetRequest verifyHttpsUrl fail");
  234. return "";
  235. }
  236. return response;
  237. }
  238. /**
  239. * httpsPost方式发送
  240. *
  241. * @return
  242. * @throws HttpException
  243. * @see
  244. * @since V1.0
  245. */
  246. public String httpsPostRequest(String servHttpsAddr, String xmlBody) {
  247. if (servHttpsAddr == null || servHttpsAddr.equals("")) {
  248. CLog.d(TAG, "postHttpsRequest servHttpsAddr == null");
  249. return "";
  250. }
  251. if (xmlBody == null || xmlBody.equals("")) {
  252. CLog.d(TAG, "postHttpsRequest xmlBody == null");
  253. return "";
  254. }
  255. boolean bRet = verifyHttpsUrl(servHttpsAddr);
  256. if (!bRet) {
  257. CLog.d(TAG, "postHttpsRequest verifyHttpsUrl fail");
  258. return "";
  259. }
  260. String response = "";
  261. try {
  262. response = postSslRequest(servHttpsAddr, xmlBody);
  263. } catch (HttpException e) {
  264. e.printStackTrace();
  265. CLog.d(TAG, "postHttpsRequest postSslRequest fail");
  266. return "";
  267. }
  268. return response;
  269. }
  270. /**
  271. * 把输入流转化成string
  272. *
  273. * @param is
  274. * @return
  275. * @see
  276. * @since V1.0
  277. */
  278. private static String inputStream2String(InputStream is) {
  279. InputStreamReader inputStreamReader = new InputStreamReader(is);
  280. BufferedReader in = new BufferedReader(inputStreamReader);
  281. StringBuffer buffer = new StringBuffer();
  282. String line = "";
  283. try {
  284. while ((line = in.readLine()) != null) {
  285. buffer.append(line);
  286. }
  287. } catch (IOException e) {
  288. e.printStackTrace();
  289. } finally {
  290. try {
  291. if (inputStreamReader != null) {
  292. inputStreamReader.close();
  293. }
  294. inputStreamReader = null;
  295. if (in != null) {
  296. in.close();
  297. }
  298. in = null;
  299. } catch (IOException e) {
  300. e.printStackTrace();
  301. }
  302. }
  303. return buffer.toString();
  304. }
  305. /**
  306. * 这里对方法做描述
  307. *
  308. * @param servHttpsAddr
  309. * @param xmlBody
  310. * @return
  311. * @throws HttpException
  312. * @since V1.0
  313. */
  314. private String getSslRequest(String servHttpsAddr) throws HttpException {
  315. // create connection
  316. String response = null;
  317. HttpURLConnection conn = null;
  318. boolean ret = false;
  319. InputStream in = null;
  320. try {
  321. URL url = new URL(servHttpsAddr);
  322. trustAllHosts();
  323. conn = (HttpsURLConnection) url.openConnection();
  324. ((HttpsURLConnection) conn).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认
  325. // ((HttpsURLConnection)
  326. // conn).setSSLSocketFactory(getPushSSLSocketFactory());
  327. conn.setConnectTimeout(mTimeOut);
  328. conn.setReadTimeout(mTimeOut);
  329. conn.setDoInput(true);
  330. conn.setRequestMethod("GET");
  331. conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");
  332. if (conn.getResponseCode() == 200) {
  333. // getCookie(conn);
  334. in = new BufferedInputStream(conn.getInputStream());
  335. } else {
  336. in = new BufferedInputStream(conn.getErrorStream());
  337. }
  338. response = inputStream2String(in);
  339. in.close();
  340. in = null;
  341. ret = true;
  342. } catch (MalformedURLException e) {
  343. ret = false;
  344. e.printStackTrace();
  345. } catch (ProtocolException e) {
  346. ret = false;
  347. e.printStackTrace();
  348. } catch (IOException e) {
  349. ret = false;
  350. e.printStackTrace();
  351. }
  352. // catch (NoSuchAlgorithmException e) {
  353. // ret = false;
  354. // e.printStackTrace();
  355. // } catch (KeyManagementException e) {
  356. // ret = false;
  357. // e.printStackTrace();
  358. // } catch (KeyStoreException e) {
  359. // ret = false;
  360. // e.printStackTrace();
  361. // } catch (CertificateException e) {
  362. // ret = false;
  363. // e.printStackTrace();
  364. // } catch (UnrecoverableKeyException e) {
  365. // ret = false;
  366. // e.printStackTrace();
  367. // }
  368. finally {
  369. if (in != null) {
  370. try {
  371. in.close();
  372. } catch (IOException e) {
  373. // TODO Auto-generated catch block
  374. e.printStackTrace();
  375. }
  376. in = null;
  377. }
  378. if (conn != null) {
  379. // 断开连接
  380. conn.disconnect();
  381. conn = null;
  382. }
  383. }
  384. // 抛出异常
  385. if (!ret) {
  386. throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
  387. }
  388. return response;
  389. }
  390. /**
  391. * 验证https地址
  392. *
  393. * @since V1.0
  394. */
  395. public boolean verifyHttpsUrl(String httpsAddr) {
  396. // TODO Auto-generated method stub
  397. if (httpsAddr == null || httpsAddr.equals("")) {
  398. CLog.e(TAG, "verifyHttpsUrl httpsAddr == null");
  399. return false;
  400. }
  401. URL httpsUurl;
  402. try {
  403. httpsUurl = new URL(httpsAddr);
  404. } catch (MalformedURLException e) {
  405. // TODO Auto-generated catch block
  406. e.printStackTrace();
  407. CLog.e(TAG, "verifyHttpsUrl httpsAddr not url, error url:" + httpsAddr);
  408. return false;
  409. }
  410. if (!httpsUurl.getProtocol().equalsIgnoreCase("https")) {
  411. CLog.e(TAG, "verifyHttpsUrl httpsAddr not https, error url:" + httpsAddr);
  412. return false;
  413. }
  414. return true;
  415. }
  416. /**
  417. * post ssl请求
  418. *
  419. * @param servHttpsAddr
  420. * @param xmlBody
  421. * @return
  422. * @throws HttpException
  423. * @since V1.0
  424. */
  425. private String postSslRequest(String servHttpsAddr, String xmlBody) throws HttpException {
  426. // 回复信令
  427. String response = null;
  428. //
  429. boolean ret = false;
  430. // 输入流
  431. InputStream in = null;
  432. DataOutputStream os = null;
  433. HttpsURLConnection httpsConn = null;
  434. InputStream inputStream = null;
  435. try {
  436. URL url = new URL(servHttpsAddr);
  437. // solution: javax.net.ssl.SSLException: Not trusted server
  438. // certificate
  439. trustAllHosts();
  440. // 打开连接
  441. httpsConn = (HttpsURLConnection) url.openConnection();
  442. // 不进行主机名确认
  443. httpsConn.setHostnameVerifier(DO_NOT_VERIFY);
  444. httpsConn.setConnectTimeout(mTimeOut);
  445. httpsConn.setReadTimeout(mTimeOut);
  446. httpsConn.setDoInput(true);
  447. httpsConn.setDoOutput(true);
  448. httpsConn.setRequestMethod("POST");
  449. httpsConn.setRequestProperty("Content-type","text/xml; charset=utf-8");
  450. // send xml contant to server
  451. os = new DataOutputStream(httpsConn.getOutputStream());
  452. os.write(xmlBody.getBytes(), 0, xmlBody.getBytes().length);
  453. os.flush();
  454. os.close();
  455. os = null;
  456. if (httpsConn.getResponseCode() == 200) {
  457. // getCookie(conn);
  458. inputStream = httpsConn.getInputStream();
  459. in = new BufferedInputStream(inputStream);
  460. } else {
  461. inputStream = httpsConn.getErrorStream();
  462. in = new BufferedInputStream(inputStream);
  463. }
  464. response = inputStream2String(in);
  465. if (inputStream != null) {
  466. inputStream.close();
  467. inputStream = null;
  468. }
  469. in.close();
  470. in = null;
  471. ret = true;
  472. } catch (MalformedURLException e) {
  473. ret = false;
  474. e.printStackTrace();
  475. } catch (ProtocolException e) {
  476. ret = false;
  477. e.printStackTrace();
  478. } catch (IOException e) {
  479. ret = false;
  480. e.printStackTrace();
  481. } finally {
  482. try {
  483. if (inputStream != null) {
  484. inputStream.close();
  485. }
  486. if (in != null) {
  487. in.close();
  488. }
  489. in = null;
  490. if (os != null) {
  491. os.close();
  492. }
  493. } catch (IOException e) {
  494. e.printStackTrace();
  495. }
  496. if (httpsConn != null) {
  497. // 断开连接
  498. httpsConn.disconnect();
  499. httpsConn = null;
  500. }
  501. }
  502. // 抛出异常
  503. if (!ret) {
  504. throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
  505. }
  506. return response;
  507. }
  508. /** always verify the host - dont check for certificate */
  509. final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
  510. public boolean verify(String hostname, SSLSession session) {
  511. return true;
  512. }
  513. };
  514. /**
  515. * Trust every server - dont check for any certificate
  516. *
  517. * @since V1.0
  518. */
  519. private static void trustAllHosts() {
  520. // Create a trust manager that does not validate certificate chains
  521. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
  522. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  523. return new java.security.cert.X509Certificate[] {};
  524. }
  525. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  526. }
  527. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  528. }
  529. } };
  530. // Install the all-trusting trust manager
  531. try {
  532. SSLContext sc = SSLContext.getInstance(CLIENT_AGREEMENT);
  533. sc.init(null, trustAllCerts, new java.security.SecureRandom());
  534. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  535. } catch (Exception e) {
  536. e.printStackTrace();
  537. }
  538. }
  539. /**
  540. * 在此对类做相应的描述 */
  541. public static class _FakeX509TrustManager implements X509TrustManager {
  542. /** 变量/常量说明 */
  543. private static TrustManager[] trustManagers;
  544. /** 变量/常量说明 */
  545. private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
  546. @Override
  547. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  548. }
  549. @Override
  550. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  551. }
  552. /**
  553. * 这里对方法做描述
  554. *
  555. * @param chain
  556. * @return
  557. * @since V1.0
  558. */
  559. public boolean isClientTrusted(X509Certificate[] chain) {
  560. return true;
  561. }
  562. /**
  563. * 这里对方法做描述
  564. *
  565. * @param chain
  566. * @return
  567. * @since V1.0
  568. */
  569. public boolean isServerTrusted(X509Certificate[] chain) {
  570. return true;
  571. }
  572. /*
  573. * (non-Javadoc)
  574. * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
  575. */
  576. @Override
  577. public X509Certificate[] getAcceptedIssuers() {
  578. return _AcceptedIssuers;
  579. }
  580. /**
  581. * 这里对方法做描述
  582. *
  583. * @since V1.0
  584. */
  585. public static void allowAllSSL() {
  586. HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
  587. @Override
  588. public boolean verify(String hostname, SSLSession session) {
  589. return true;
  590. }
  591. });
  592. SSLContext context = null;
  593. if (trustManagers == null) {
  594. trustManagers = new TrustManager[] { new _FakeX509TrustManager() };
  595. }
  596. try {
  597. context = SSLContext.getInstance(CLIENT_AGREEMENT);
  598. if (context == null) {
  599. return;
  600. }
  601. context.init(null, trustManagers, new SecureRandom());
  602. SSLSocketFactory defaultSSLSocketFactory = context.getSocketFactory();
  603. if (defaultSSLSocketFactory != null) {
  604. HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
  605. }
  606. } catch (NoSuchAlgorithmException e) {
  607. e.printStackTrace();
  608. } catch (KeyManagementException e) {
  609. e.printStackTrace();
  610. }
  611. }
  612. }
  613. }

复制代码

发表评论

表情:
评论列表 (有 0 条评论,247人围观)

还没有评论,来说两句吧...

相关阅读

    相关 android 发送http请求

    好久没写博客了,因为公司要做android,笔者也是第一次接触。 这是在项目中遇到一个比较麻烦的问题,记录下来备忘(本人刚接触,有不对的地方请指教)。 发送请求的