目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar)

1. 建立一个连接配置类
Java代码
  1. classUserAgentConfig{
  2. publicStringhost;
  3. publicStringscheme="http";
  4. publicintport=80;
  5. publicinttimeoutConnection=3000;
  6. publicinttimeoutSocket=20000;
  7. publicStringusername="";
  8. publicStringpassword="";
  9. }

2. 封装请求类
Java代码
  1. publicclassHttpRequest{
  2. /**
  3. *get"Stream"asresponse
  4. *
  5. *@paramurlrequestURL
  6. *@paramconfigconnectionconfig,canbenull
  7. *@paramparamsparameterforpostmethod,canbenull
  8. *@returnresponseinstream
  9. */
  10. publicstaticInputStreamgetStream(Stringurl,UserAgentConfigconfig,
  11. List<BasicNameValuePair>params){
  12. HttpEntityentity=httprequest(url,config,params);
  13. InputStreamret=null;
  14. if(entity!=null){
  15. try{
  16. byte[]b=EntityUtils.toByteArray(entity);
  17. ret=newByteArrayInputStream(b);
  18. }catch(Exceptione){
  19. e.printStackTrace();
  20. }finally{
  21. release(entity);
  22. }
  23. }
  24. returnret;
  25. }
  26. /**
  27. *get"String"asresponse
  28. *
  29. *@paramurlrequestURL
  30. *@paramconfigconnectionconfig,canbenull
  31. *@paramparamsparameterforpostmethod,canbenull
  32. *@returnresponseinstring
  33. */
  34. publicstaticStringgetString(Stringurl,UserAgentConfigconfig,
  35. List<BasicNameValuePair>params){
  36. HttpEntityentity=httprequest(url,config,params);
  37. Stringret=null;
  38. if(entity!=null){
  39. try{
  40. ret=EntityUtils.toString(entity);
  41. }catch(Exceptione){
  42. e.printStackTrace();
  43. }finally{
  44. release(entity);
  45. }
  46. }
  47. returnret;
  48. }
  49. privatestaticvoidrelease(HttpEntityentity){
  50. try{
  51. entity.consumeContent();
  52. }catch(IOExceptione){
  53. e.printStackTrace();
  54. }
  55. }
  56. /**
  57. *get"HttpEntity"asresponse
  58. *
  59. *@paramurlrequestURL
  60. *@paramconfigconnectionconfig,canbenull
  61. *@paramparamsparameterforpostmethod,canbenull
  62. *@return
  63. */
  64. privatestaticHttpEntityhttprequest(Stringurl,UserAgentConfigconfig,
  65. List<BasicNameValuePair>params){
  66. DefaultHttpClientclient=null;
  67. HttpEntityentity=null;
  68. try{
  69. BasicHttpParamshttpParameters=newBasicHttpParams();
  70. if(config!=null){
  71. //setconnectiontimeout
  72. HttpConnectionParams.setConnectionTimeout(httpParameters,
  73. config.timeoutConnection);
  74. HttpConnectionParams.setSoTimeout(httpParameters,
  75. config.timeoutSocket);
  76. }
  77. client=newDefaultHttpClient(httpParameters);
  78. DefaultHttpRequestRetryHandlerretryHandler=newDefaultHttpRequestRetryHandler(
  79. 3,true);
  80. client.setHttpRequestRetryHandler(retryHandler);
  81. //setusername&passwordifavailable
  82. if(config!=null
  83. &&!("".equals(config.username)&&""
  84. .equals(config.password))){
  85. AuthScopeas=newAuthScope(config.host,config.port);
  86. UsernamePasswordCredentialsupc=newUsernamePasswordCredentials(
  87. config.username,config.password);
  88. client.getCredentialsProvider().setCredentials(as,upc);
  89. }
  90. //checkgetorpostmethodbyparams
  91. HttpRequestBasemethod=null;
  92. if(params==null){
  93. method=newHttpGet(url);
  94. }else{
  95. method=newHttpPost(url);
  96. ((HttpPost)method).setEntity(newUrlEncodedFormEntity(params,
  97. "utf-8"));
  98. }
  99. method.setHeader("Content-Type","application/xml");
  100. //getresponse
  101. HttpResponseresponse=null;
  102. if(config==null){
  103. //onlyurlisavailable
  104. response=client.execute(method);
  105. }else{
  106. BasicHttpContextlocalContext=newBasicHttpContext();
  107. BasicSchemebasicAuth=newBasicScheme();
  108. localContext.setAttribute("preemptive-auth",basicAuth);
  109. HttpHosttargetHost=newHttpHost(config.host,config.port,
  110. config.scheme);
  111. response=client.execute(targetHost,method,localContext);
  112. }
  113. entity=response.getEntity();
  114. }catch(Exceptione){
  115. e.printStackTrace();
  116. }
  117. returnentity;
  118. }
  119. }

3. 调用
GET请求
Java代码
  1. Stringurl="...";
  2. test(url,null,null);

Java代码
  1. Stringurl="...";
  2. UserAgentConfigconfig=newUserAgentConfig();
  3. config.host="...";
  4. test(url,config,null);

POST请求
Java代码
  1. Stringurl="...";
  2. UserAgentConfigconfig=newUserAgentConfig();
  3. config.host="...";
  4. config.username="...";
  5. config.password="...";
  6. ArrayList<BasicNameValuePair>params=newArrayList<BasicNameValuePair>();
  7. params.add(newBasicNameValuePair("...","..."));
  8. ...
  9. test(url,config,params);

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. Nginx系列教程(六)| 手把手教你搭建 LNMP 架构并部署天空网络电影
  3. Android类似于滚动的通知栏实现
  4. Android性能分析工具Systrace和TraceView,性能测试GT等
  5. Android中双击返回键退出应用实例代码
  6. 实现activity全屏显示
  7. android代码power off 以及特定文件格式的使用
  8. 如何解决Eclipse中Android(安卓)代码自动补全卡死的问题
  9. Android网络访问与数据解析

随机推荐

  1. navicat for mysql 注册码,简简单单,一个搞
  2. MySQL数据库语法-多表查询练习一
  3. MySQL - 更改一行的时间值以匹配同一表
  4. php将图片以二进制形式保存到mysql数据库
  5. 为什么插入忽略递增的auto_increment主键
  6. 解决The&#39;InnoDB&#39;feature is disa
  7. mysql常识以及存储引擎,锁和事务
  8. 05-mysql中的查询(第一章)
  9. Active Record或mysql中的批次计数
  10. Innode表空间碎片优化