Http网络连接处理

Http网络连接处理

这里我们将学习Android程序如何进行网络连接,获取网络返回数据,如果对HTTP网络协议还不了解的可以参考深入理解HTTP协议,在进行网络连接操作前需要先在程序的manifest文件中添加下面的permissions:

1 <uses-permission android:name="android.permission.INTERNET" />
2 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

同时要检查当前网络环境是否可用

1 ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
2 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
3 if (networkInfo != null && networkInfo.isConnected()) {
4     //网络连接可用
5 else {
6     //网络连接不可用!
7 }

网络操作会遇到不可预期的延迟。显然为了避免一个不好的用户体验,总是在UI Thread之外去执行网络操作。AsyncTask 类提供了一种简单的方式来处理这个问题
doInBackground()) 执行 downloadUrl()方法。Web URL作为参数,方法downloadUrl() 获取并处理网页返回的数据,执行完毕后,传递结果到onPostExecute()。参数类型为String.
onPostExecute()) 获取到返回数据并显示到UI上。

1 private class DownloadWebpageText extends AsyncTask<String, Void, String> {
2         @Override
3         protected String doInBackground(String... urls) {
4  
5             // 参数从execute()方法传入, params[0]表示url.
6             //获取url资源数据并返回
7         }
8  
9         // onPostExecute方法中处理AsyncTask返回的结果
10         @Override
11         protected void onPostExecute(String result) {
12  
13         }
14  
15     }

我们来看下完整的实例代码
布局文件activity_httpconnection_layout.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3     android:layout_width="match_parent"
4     android:layout_height="match_parent"
5     android:orientation="vertical" >
6  
7     <EditText
8         android:id="@+id/http_url_edit"
9         android:layout_width="match_parent"
10         android:layout_height="wrap_content"
11         android:hint="请输入URL地址" />
12  
13     <TextView
14         android:id="@+id/http_content_txt"
15         android:layout_width="match_parent"
16         android:layout_height="wrap_content" />
17  
18     <Button android:id="@+id/http_get_content_btn"
19         android:layout_width="match_parent"
20         android:onClick="onConnectionClickHandler"
21         android:layout_height="wrap_content" />
22  
23 </LinearLayout>

原代码 HttpExampleActivity.java

1 public class HttpExampleActivity extends Activity {
2     private static final String DEBUG_TAG = "HttpExample";
3     private EditText mUrlText;
4     private TextView mShowMessageTxt;
5  
6     @Override
7     public void onCreate(Bundle savedInstanceState) {
8         super.onCreate(savedInstanceState);
9         setContentView(R.layout.activity_httpconnection_layout);
10         mUrlText = (EditText) findViewById(R.id.http_url_edit);
11         mShowMessageTxt = (TextView) findViewById(R.id.http_content_txt);
12     }
13  
14     /**
15      * 用户点击此按钮时执行异步任务,在执行前需检查网络是否可用.
16      *
17      */
18     public void onConnectionClickHandler(View view) {
19         String stringUrl = mUrlText.getText().toString();// 获取请求的URL从EditText控件中.
20         ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
21         NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
22         if (networkInfo != null && networkInfo.isConnected()) {
23             new DownloadWebpageText().execute(stringUrl);
24         else {
25             mShowMessageTxt.setText("网络连接不可用!");
26         }
27     }
28  
29     private class DownloadWebpageText extends AsyncTask<String, Void, String> {
30         @Override
31         protected String doInBackground(String... urls) {
32  
33             // 参数从execute()方法传入, params[0]表示url.
34             try {
35                 return downloadUrl(urls[0]);
36             catch (IOException e) {
37                 return "Unable to retrieve web page. URL may be invalid.";
38             }
39         }
40  
41         // onPostExecute方法中处理AsyncTask返回的结果
42         @Override
43         protected void onPostExecute(String result) {
44             mShowMessageTxt.setText(result);
45         }
46  
47     }
48  
49     /**
50      * 根据给定的url地址,建立一个HttpUrlConnection连接它将以流的形式返回页面内容,将流转换成字符串返回
51      * @param myurl
52      * @return
53      * @throws IOException
54      */
55     private String downloadUrl(String myurl) throws IOException {
56         InputStream is = null;
57  
58         try {
59             URL url = new URL(myurl);
60             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
61             conn.setReadTimeout(10000);  /*读数据超时*/
62             conn.setConnectTimeout(15000);/*连接超时*/
63             conn.setRequestMethod("GET"); /*请求方式*/
64             conn.setDoInput(true);/* 设置允许输入流*/
65  
66             conn.connect();
67             int response = conn.getResponseCode();
68             Log.d(DEBUG_TAG, "The response is: " + response);
69             is = conn.getInputStream();
70  
71             String contentAsString = readIt(is);
72             return contentAsString;
73  
74             //关闭InputStream
75         } finally {
76             if (is != null) {
77                 is.close();
78             }
79         }
80     }
81  
82     /**
83      * 将InputStream转换成String返回
84      * @param stream
85      * @return
86      * @throws IOException
87      * @throws UnsupportedEncodingException
88      */
89     public String readIt(InputStream stream) throwsIOException,UnsupportedEncodingException {
90         Reader reader = new InputStreamReader(stream, "UTF-8");
91         // 创建包装流
92         BufferedReader br = new BufferedReader(reader);
93         // 定义String类型用于储存单行数据
94         String line = null;
95         // 创建StringBuffer对象用于存储所有数据
96         StringBuffer sb = new StringBuffer();
97         while ((line = br.readLine()) != null) {
98             sb.append(line);
99         }
100  
101         return sb.toString();
102  
103     }
104  
105 }

请注意,getResponseCode() 会返回连接状态码( status code). 这是一种获知额外网络连接信息的有效方式。status code 是 200 则意味着连接成功.

Convert the InputStream to a String(把InputStream的数据转换为String)
InputStream 是一种可读的byte数据源。如果你获得了一个 InputStream, 通常会进行decode或者转换为制定的数据类型。例如,如果你是在下载一张image数据,你可能需要像下面一下进行decode:

1 InputStream is = null;
2 ...
3 Bitmap bitmap = BitmapFactory.decodeStream(is);
4 ImageView imageView = (ImageView) findViewById(R.id.image_view);
5 imageView.setImageBitmap(bitmap);

大多数连接网络的Android app会使用HttpURLConnection作为客户端来发送与接受数据。除此之外还可用Apache HttpClient。

1 HttpClient httpClient = new DefaultHttpClient();
2             HttpGet httpGet = new HttpGet(httpUrl);
3             HttpResponse response = httpClient.execute(httpGet);
4  
5             int statusCode = response.getStatusLine().getStatusCode();
6             Logs.v("statusCode >>> :" + statusCode);
7  
8             if (statusCode == HttpURLConnection.HTTP_OK) {
9                 InputStream ins = response.getEntity().getContent();
10  
11                 BufferedReader br = new BufferedReader(newInputStreamReader(ins,"utf-8"));
12  
13                 StringBuilder sb = new StringBuilder();
14                 String line = null;
15                 while ((line = br.readLine()) != null) {
16                     sb.append(line);
17                 }
18  
19             }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值