Use the android built-in HTTP package for network requests

Source: Internet
Author: User

Reprinted from http://dai-lm.iteye.com/blog/1160191

1. Create a connection configuration class

  1. Class useragentconfig {
  2. Public String host;
  3. Public String scheme = "HTTP ";
  4. Public int Port = 80;
  5. Public int timeoutconnection = 3000;
  6. Public int timeoutsocket = 20000;
  7. Public String username = "";
  8. Public String Password = "";
  9. }

2. encapsulate the request class

  1. Public class httprequest {
  2. /**
  3. * Get "stream" as response only based on URL
  4. *
  5. * @ Param strurl
  6. * @ Return
  7. */
  8. Public static inputstream getstream (string strurl ){
  9. Inputstream input = NULL;
  10. Try {
  11. URL url = new URL (strurl );
  12. Httpurlconnection urlcon = (httpurlconnection) URL. openconnection ();
  13. Input = urlcon. getinputstream ();
  14. } Catch (ioexception e ){
  15. E. printstacktrace ();
  16. }
  17. Return input;
  18. }
  19. /**
  20. * Get "stream" as response
  21. *
  22. * @ Param URL request URL
  23. * @ Param config connection config
  24. * @ Param Params parameter for post method
  25. * @ Return response in stream
  26. * @ Throws ioexception
  27. * @ Throws illegalstateexception
  28. */
  29. Public static inputstream getstream (string URL, useragentconfig config,
  30. List <basicnamevaluepair> Params ){
  31. Httpentity entity = httprequest (URL, config, Params );
  32. Inputstream ret = NULL;
  33. If (entity! = NULL ){
  34. Try {
  35. Byte [] B = entityutils. tobytearray (entity );
  36. Ret = new bytearrayinputstream (B );
  37. } Catch (exception e ){
  38. E. printstacktrace ();
  39. } Finally {
  40. Release (entity );
  41. }
  42. }
  43. Return ret;
  44. }
  45. /**
  46. * Get "string" as response
  47. *
  48. * @ Param URL
  49. * @ Param config
  50. * @ Param Params
  51. * @ Return
  52. */
  53. Public static string getstring (string URL, useragentconfig config,
  54. List <basicnamevaluepair> Params ){
  55. Httpentity entity = httprequest (URL, config, Params );
  56. String ret = NULL;
  57. If (entity! = NULL ){
  58. Try {
  59. Ret = entityutils. tostring (entity );
  60. } Catch (exception e ){
  61. E. printstacktrace ();
  62. } Finally {
  63. Release (entity );
  64. }
  65. }
  66. Return ret;
  67. }
  68. Private Static void release (httpentity entity ){
  69. Try {
  70. Entity. consumecontent ();
  71. } Catch (ioexception e ){
  72. E. printstacktrace ();
  73. }
  74. }
  75. /**
  76. * Get "httpentity" as response
  77. *
  78. * @ Param URL request URL
  79. * @ Param config connection config
  80. * @ Param Params parameter for post method
  81. * @ Return
  82. */
  83. Private Static httpentity httprequest (string URL, useragentconfig config,
  84. List <basicnamevaluepair> Params ){
  85. Defaulthttpclient client = NULL;
  86. Httpentity entity = NULL;
  87. Try {
  88. Basichttpparams httpparameters = new basichttpparams ();
  89. // Set connection timeout
  90. Httpconnectionparams. setconnectiontimeout (httpparameters,
  91. Config. timeoutconnection );
  92. Httpconnectionparams. setsotimeout (httpparameters,
  93. Config. timeoutsocket );
  94. Client = new defaulthttpclient (httpparameters );
  95. // Retry 3 times
  96. Defaulthttprequestretryhandler retryhandler = new defaulthttprequestretryhandler (3, true );
  97. Client. sethttprequestretryhandler (retryhandler );
  98. // Set username & password if available
  99. If (! ("". Equals (config. username) & "". Equals (config. Password ))){
  100. Authscope as = new authscope (config. Host, config. Port );
  101. Usernamepasswordcredentials UPC = new usernamepasswordcredentials (
  102. Config. username, config. Password );
  103. Client. getcredentialsprovider (). setcredentials (AS, UPC );
  104. }
  105. Basichttpcontext localcontext = new basichttpcontext ();
  106. Basicscheme basicauth = new basicscheme ();
  107. Localcontext. setattribute ("preemptive-auth", basicauth );
  108. Httphost targethost = new httphost (config. Host, config. Port,
  109. Config. scheme );
  110. // Check get or POST method by Params
  111. Httprequestbase method = NULL;
  112. If (Params = NULL ){
  113. Method = new httpget (URL );
  114. } Else {
  115. Method = new httppost (URL );
  116. (Httppost) method). setentity (New urlencodedformentity (Params,
  117. "UTF-8 "));
  118. }
  119. Method. setheader ("Content-Type", "application/XML ");
  120. Httpresponse response = client.exe cute (targethost, method,
  121. Localcontext );
  122. Entity = response. getentity ();
  123. } Catch (exception e ){
  124. E. printstacktrace ();
  125. }
  126. Return entity;
  127. }
  128. }

3. Call
GET request

  1. String url = "...";
  2. Useragentconfig Config = new useragentconfig ();
  3. Config. Host = "...";
  4. Test (URL, config, null );

POST request

  1. String url = "...";
  2. Useragentconfig Config = new useragentconfig ();
  3. Config. Host = "...";
  4. Config. Username = "...";
  5. Config. Password = "...";
  6. Arraylist <basicnamevaluepair> Params = new arraylist <basicnamevaluepair> ();
  7. Params. Add (New basicnamevaluepair ("...","..."));
  8. ...
  9. Test (URL, config, Params );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.