免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1861 | 回复: 1
打印 上一主题 下一主题

[Android] HttpURLConnection&HttpClient网络通信 (搬运) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-08-12 14:08 |只看该作者 |倒序浏览
本帖最后由 taony76 于 2015-08-12 14:09 编辑

一:HttpURLConnection简介:

  用于发送或者接受HTTP协议请求的类,获得的数据可以是任意类型和长度,这个类可以用于发送和接收流数据,其长度事先不知道。

  使用这个类遵循一下模式:
1.获得一个新的HttpURLConnection通过调用URL.openConnection()获得一个HttpURLConnection实例。
2.准备请求。请求的主要特性是它的URI。请求头也可以包括元数据,如凭证,首选的内容类型和会话cookie。
3.可选择上传请求主体。实例必须配置 setDoOutput(true),如果他们有一个请求主体。以书面形式向被返回的流的getOutputStream.
4.读取响应。响应头通常包括元数据,如响应主体的内容类型和长度,修改日期和会话Cookie。响应体可以从返回的流中的getInputStream。如果响应没有主体,该方法返回一个空流。
5.断开。一旦响应体已被读取时,HttpURLConnection的应该调用关闭disconnect()。断开释放一个连接持有的资源,所以他们可能被关闭或重新使用。


       如下:是通过HttpURLConnection或的数据的例子:
  1. 网址url =  new URL ( "http://www.android.com/" );
  2.    HttpURLConnection urlConnection =  ( HttpURLConnection ) url . openConnection ();
  3.    try  {
  4.      InputStream  in  =  new  BufferedInputStream ( urlConnection . getInputStream ());
  5.      readStream ( in );
  6.      finally  {
  7.      urlConnection . disconnect ();
  8.    }
复制代码
HttpURLConnection详细功能,请参照谷歌官方API:http://developer.android.com/ref ... pURLConnection.html



  HttpClient简介:

  接口的HTTP客户端。HTTP客户端封装执行HTTP请求,同时处理Cookie,认证,连接管理等功能所需对象的大杂烩。HTTP客户端的线程安全依赖于特定的客户端的实现和配置。

  该类不建议在API22上使用。

  常用的公共方法有:

  1:execute(HttpUriRequest request);     执行使用默认情况下的请求.


  2: getConnectionManager();                获得使用该客户端的连接管理器。

  3: getParams();                                  获得参数,这个用于客户端。

      HttpClient这个类比较简单,详细的信息可以参照谷歌官方API:  http://developer.android.com/ref ... ent/HttpClient.html



二:通过一个简单的Demo来分别实现HttpURLConnection和HttpClient的GET和POST请求。

  展示如下,非常简单:

2:Activity中代码实现如下:

  (注:因为HTTP网络请求是耗时操作,所以在android开发中,为避免耗时操作阻塞主线程,

   需使用子线程或这一步操作实现这些耗时操作。本例中使用的是AsyncTast异步处理。)
  1. 1 package activity.cyq.httplearn;
  2.   2
  3.   3 import android.os.AsyncTask;
  4.   4 import android.support.v7.app.AppCompatActivity;
  5.   5 import android.os.Bundle;
  6.   6 import android.view.View;
  7.   7 import android.widget.Button;
  8.   8 import android.widget.TextView;
  9.   9
  10. 10 import org.apache.http.HttpResponse;
  11. 11 import org.apache.http.client.HttpClient;
  12. 12 import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. 13 import org.apache.http.client.methods.HttpGet;
  14. 14 import org.apache.http.client.methods.HttpPost;
  15. 15 import org.apache.http.impl.client.DefaultHttpClient;
  16. 16 import org.apache.http.message.BasicNameValuePair;
  17. 17 import org.apache.http.util.EntityUtils;
  18. 18
  19. 19 import java.io.BufferedReader;
  20. 20 import java.io.BufferedWriter;
  21. 21 import java.io.IOException;
  22. 22 import java.io.InputStream;
  23. 23 import java.io.InputStreamReader;
  24. 24 import java.io.OutputStream;
  25. 25 import java.io.OutputStreamWriter;
  26. 26 import java.io.UnsupportedEncodingException;
  27. 27 import java.net.HttpURLConnection;
  28. 28 import java.net.MalformedURLException;
  29. 29 import java.net.URL;
  30. 30 import java.net.URLConnection;
  31. 31 import java.util.ArrayList;
  32. 32 import java.util.List;
  33. 33
  34. 34 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  35. 35
  36. 36     private Button HTTP_GET, HTTP_POST, HTTPClinet_GET, HTTPClient_P0st;
  37. 37     private TextView dataShow;
  38. 38     private final String urlStr = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3";
  39. 39     private final String urlPost = "http://apis.juhe.cn/mobile/get";
  40. 40     private String phone = "1342966";/*手机号码前七位*/
  41. 41     private final String key = "a26da09113eaf8bd24456f0bd4037eb3";
  42. 42
  43. 43     @Override
  44. 44     protected void onCreate(Bundle savedInstanceState) {
  45. 45         super.onCreate(savedInstanceState);
  46. 46         setContentView(R.layout.activity_main);
  47. 47
  48. 48         HTTP_GET = (Button) findViewById(R.id.HTTP_GetBTN);
  49. 49         HTTP_POST = (Button) findViewById(R.id.HTTP_PostBTN);
  50. 50         HTTPClinet_GET = (Button) findViewById(R.id.HTTPClient_GetBTN);
  51. 51         HTTPClient_P0st = (Button) findViewById(R.id.HTTPClient_PostBTN);
  52. 52         dataShow = (TextView) findViewById(R.id.dataShowText);
  53. 53
  54. 54         HTTP_GET.setOnClickListener(this);
  55. 55         HTTP_POST.setOnClickListener(this);
  56. 56         HTTPClinet_GET.setOnClickListener(this);
  57. 57         HTTPClient_P0st.setOnClickListener(this);
  58. 58
  59. 59     }
  60. 60
  61. 61
  62. 62     @Override
  63. 63     public void onClick(View v) {
  64. 64         switch (v.getId()) {
  65. 65             case R.id.HTTP_GetBTN:
  66. 66                 new AsyncTask<String, Void, String>() {
  67. 67                     @Override
  68. 68                     protected String doInBackground(String... params) {
  69. 69                         try {
  70. 70                             URL url = new URL(params[0]);
  71. 71                             URLConnection connection = url.openConnection();
  72. 72                             InputStream is = connection.getInputStream();
  73. 73                             InputStreamReader isr = new InputStreamReader(is);
  74. 74                             BufferedReader br = new BufferedReader(isr);
  75. 75                             String line;
  76. 76                             StringBuilder sBuilder = new StringBuilder();
  77. 77                             while ((line = br.readLine()) != null) {
  78. 78                                 sBuilder.append(line);
  79. 79                             }
  80. 80                             br.close();
  81. 81                             isr.close();
  82. 82                             is.close();
  83. 83                             return "HTTP_GET请求方式数据结果:" + sBuilder.toString();
  84. 84
  85. 85                         } catch (MalformedURLException e) {
  86. 86                             e.printStackTrace();
  87. 87                         } catch (IOException e) {
  88. 88                             e.printStackTrace();
  89. 89                         }
  90. 90                         return null;
  91. 91                     }
  92. 92
  93. 93                     @Override
  94. 94                     protected void onPostExecute(String s) {
  95. 95                         dataShow.append(s);
  96. 96                         super.onPostExecute(s);
  97. 97                     }
  98. 98                 }.execute(urlStr);
  99. 99                 break;
  100. 100             case R.id.HTTP_PostBTN:
  101. 101                 new AsyncTask<String, Void, String>() {
  102. 102                     @Override
  103. 103                     protected String doInBackground(String... params) {
  104. 104                         URL url = null;
  105. 105                         try {
  106. 106                             url = new URL(params[0]);
  107. 107                             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  108. 108
  109. 109                             connection.setRequestMethod("POST");
  110. 110                             connection.setReadTimeout(8000);
  111. 111                             connection.setConnectTimeout(1000);
  112. 112
  113. 113                             OutputStream os = connection.getOutputStream();
  114. 114                             OutputStreamWriter osw = new OutputStreamWriter(os);
  115. 115                             BufferedWriter bw = new BufferedWriter(osw);
  116. 116                             bw.write("phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3");
  117. 117                             bw.close();
  118. 118                             osw.close();
  119. 119                             os.close();
  120. 120
  121. 121                             InputStream is = connection.getInputStream();
  122. 122                             InputStreamReader isr = new InputStreamReader(is);
  123. 123                             BufferedReader br = new BufferedReader(isr);
  124. 124                             String line;
  125. 125                             StringBuilder sBuilder = new StringBuilder();
  126. 126                             while ((line = br.readLine()) != null) {
  127. 127                                 sBuilder.append(line);
  128. 128                             }
  129. 129                             br.close();
  130. 130                             isr.close();
  131. 131                             is.close();
  132. 132                             return "HTTP_POST请求方式数据结果:" + sBuilder.toString();
  133. 133
  134. 134                         } catch (MalformedURLException e) {
  135. 135                             e.printStackTrace();
  136. 136                         } catch (IOException e) {
  137. 137                             e.printStackTrace();
  138. 138                         }
  139. 139                         return null;
  140. 140                     }
  141. 141
  142. 142                     @Override
  143. 143                     protected void onPostExecute(String s) {
  144. 144                         dataShow.append(s);
  145. 145                         super.onPostExecute(s);
  146. 146                     }
  147. 147                 }.execute(urlStr);
  148. 148                 break;
  149. 149             case R.id.HTTPClient_GetBTN:
  150. 150                 new AsyncTask<String, Void, String>() {
  151. 151                     @Override
  152. 152                     protected String doInBackground(String... params) {
  153. 153
  154. 154                         HttpClient client = new DefaultHttpClient();
  155. 155                         HttpGet get = new HttpGet(params[0]);
  156. 156                         try {
  157. 157                             HttpResponse response = client.execute(get);
  158. 158                             if (response.getStatusLine().getStatusCode() == 200) {
  159. 159                                 String result = EntityUtils.toString(response.getEntity());
  160. 160                                 return result;
  161. 161                             }
  162. 162                         } catch (IOException e) {
  163. 163                             e.printStackTrace();
  164. 164                         }
  165. 165                         return null;
  166. 166                     }
  167. 167
  168. 168                     @Override
  169. 169                     protected void onPostExecute(String s) {
  170. 170                         dataShow.append("HTTPClient_Get请求方式数据结果:" + s);
  171. 171                         super.onPostExecute(s);
  172. 172                     }
  173. 173
  174. 174                 }.execute(urlStr);
  175. 175                 break;
  176. 176             case R.id.HTTPClient_PostBTN:
  177. 177                 new AsyncTask<String, Void, String>() {
  178. 178                     @Override
  179. 179                     protected String doInBackground(String... params) {
  180. 180
  181. 181                         int photoStr = Integer.parseInt(params[1]);
  182. 182                         HttpClient client = new DefaultHttpClient();
  183. 183                         HttpPost post = new HttpPost(params[0]);
  184. 184                         List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
  185. 185                         list.add(new BasicNameValuePair("phone", "13429667914"));
  186. 186                         list.add(new BasicNameValuePair("key", "a26da09113eaf8bd24456f0bd4037eb3"));
  187. 187
  188. 188                         try {
  189. 189                             post.setEntity(new UrlEncodedFormEntity(list));
  190. 190                         } catch (UnsupportedEncodingException e) {
  191. 191                             e.printStackTrace();
  192. 192                         }
  193. 193
  194. 194                         try {
  195. 195                             HttpResponse response = client.execute(post);
  196. 196                             if (response.getStatusLine().getStatusCode() == 200) {
  197. 197                                 String result = EntityUtils.toString(response.getEntity());
  198. 198                                 return result;
  199. 199                             }
  200. 200                         } catch (IOException e) {
  201. 201                             e.printStackTrace();
  202. 202                         }
  203. 203                         return null;
  204. 204                     }
  205. 205
  206. 206                     @Override
  207. 207                     protected void onPostExecute(String s) {
  208. 208                         dataShow.append("HTTPClient_POST请求方式数据结果:" + s);
  209. 209                         super.onPostExecute(s);
  210. 210                     }
  211. 211                 }.execute(urlPost, phone, key);
  212. 212                 break;
  213. 213
  214. 214         }
  215. 215
  216. 216     }
  217. 217 }
复制代码

论坛徽章:
80
20周年集字徽章-庆
日期:2020-10-28 14:09:1215-16赛季CBA联赛之北京
日期:2020-10-28 13:32:5315-16赛季CBA联赛之北控
日期:2020-10-28 13:32:4815-16赛季CBA联赛之天津
日期:2020-10-28 13:13:35黑曼巴
日期:2020-10-28 12:29:1520周年集字徽章-周	
日期:2020-10-31 15:10:0720周年集字徽章-20	
日期:2020-10-31 15:10:07ChinaUnix元老
日期:2015-09-29 11:56:3020周年集字徽章-年
日期:2020-10-28 14:14:56
2 [报告]
发表于 2015-08-13 09:34 |只看该作者
恩恩 搬运的不错。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP