做设计什么兼职网站建设,wordpress 营销模板下载,中国制造外贸网,网站漂浮怎么做原文地址#xff1a;http://android.xsoftlab.net/training/basics/network-ops/index.html
引言
这节课将会学习最基本的网络连接#xff0c;监视网络连接状况及网络控制等内容。除此之外还会附带描述如何解析、使用XML数据。
这节课所包含的示例代码演示了最基本的网络操…原文地址http://android.xsoftlab.net/training/basics/network-ops/index.html
引言
这节课将会学习最基本的网络连接监视网络连接状况及网络控制等内容。除此之外还会附带描述如何解析、使用XML数据。
这节课所包含的示例代码演示了最基本的网络操作过程。开发者可以将这部分的代码作为应用程序最基本的网络操作代码。
通过这节课的学习将会学到最基本的网络下载及数据解析的相关知识。 Note: 可以查看课程Transmitting Network Data Using Volley学习Volley的相关知识。这个HTTP库可以使网络操作更方便更快捷。Volley是一个开源框架库可以使应用的网络操作顺序更加合理并善于管理还会改善应用的相关性能。 连接到网络
这节课将会学习如何实现一个含有网络连接的简单程序。课程中所描述的步骤是网络连接的最佳实现过程。
如果应用要使用网络操作那么清单文件中应该包含以下权限
uses-permission android:nameandroid.permission.INTERNET /
uses-permission android:nameandroid.permission.ACCESS_NETWORK_STATE /
选择HTTP客户端
大多数的Android应用使用HTTP来发送、接收数据。Android中包含了两个HTPP客户端HttpURLConnection及Apache的HTTP客户端。两者都支持HTTPS上传下载超时时间配置IPv6连接池。我们推荐在Gingerbread及以上的版本中使用HttpURLConnection。有关这个话题的更多讨论信息请参见博客Android’s HTTP Clients.
检查网络连接状况
在尝试连接到网络之前应当通过getActiveNetworkInfo()方法及isConnected()方法检查网络连接是否可用。要记得设备可能处于不在网络范围的情况中也可能用户并没有开启WIFI或者移动数据。该话题的更多信息请参见 Managing Network Usage.
public void myClickHandler(View view) {...ConnectivityManager connMgr (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo connMgr.getActiveNetworkInfo();if (networkInfo ! null networkInfo.isConnected()) {// fetch data} else {// display error}...
}
在子线程中执行网络操作
网络操作所用的时间通常是不确定的。为了防止由于网络操作而引起的糟糕的用户体验应该将这个过程放入独立的线程中执行。AsyncTask类为这种实现提供了帮助。更多该话题的讨论请参见Multithreading For Performance。
在下面的代码段中myClickHandler()方法调用了new DownloadWebpageTask().execute(stringUrl)。类DownloadWebpageTask是AsyncTask的子类。DownloadWebpageTask实现了AsyncTask的以下方法
doInBackground()中执行了downloadUrl()方法。它将Web页的URL地址作为参数传给了该方法。downloadUrl()方法会获得并处理Web页面的内容。当处理结束时这个方法会将处理后的结果返回。onPostExecute()获得返回后的结果将其显示在UI上。
public class HttpExampleActivity extends Activity {private static final String DEBUG_TAG HttpExample;private EditText urlText;private TextView textView;Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main); urlText (EditText) findViewById(R.id.myUrl);textView (TextView) findViewById(R.id.myText);}// When user clicks button, calls AsyncTask.// Before attempting to fetch the URL, makes sure that there is a network connection.public void myClickHandler(View view) {// Gets the URL from the UIs text field.String stringUrl urlText.getText().toString();ConnectivityManager connMgr (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo connMgr.getActiveNetworkInfo();if (networkInfo ! null networkInfo.isConnected()) {new DownloadWebpageTask().execute(stringUrl);} else {textView.setText(No network connection available.);}}// Uses AsyncTask to create a task away from the main UI thread. This task takes a // URL string and uses it to create an HttpUrlConnection. Once the connection// has been established, the AsyncTask downloads the contents of the webpage as// an InputStream. Finally, the InputStream is converted into a string, which is// displayed in the UI by the AsyncTasks onPostExecute method.private class DownloadWebpageTask extends AsyncTaskString, Void, String {Overrideprotected String doInBackground(String... urls) {// params comes from the execute() call: params[0] is the url.try {return downloadUrl(urls[0]);} catch (IOException e) {return Unable to retrieve web page. URL may be invalid.;}}// onPostExecute displays the results of the AsyncTask.Overrideprotected void onPostExecute(String result) {textView.setText(result);}}...
}
上面的代码执行了以下操作
1.当用户按下按钮时会调用myClickHandler()方法应用会将指定的URL地址传递给DownloadWebpageTask。2.DownloadWebpageTask的doInBackground()方法调用了downloadUrl()方法。3.downloadUrl()方法将获得的URL字符串作为参数创建了一个URL对象。4.URL对象被用来与HttpURLConnection建立连接。5.一旦连接建立HttpURLConnection会将获取到的Web页面内容作为输入流输入。6.readIt()方法将输入流转换为String对象。7.最后onPostExecute()方法将String对象显示在UI上。
连接与下载数据
在执行网络传输的线程中可以使用HttpURLConnection来执行GET请求并下载输入。在调用了connect()方法之后可以通过getInputStream()方法获得输入流形式的数据。
在doInBackground()方法中调用了downloadUrl()方法。downloadUrl()方法将URL作为参数通过HttpURLConnection与网络建立连接。一旦连接建立应用通过getInputStream()方法来接收字节流形式的数据。
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {InputStream is null;// Only display the first 500 characters of the retrieved// web page content.int len 500;try {URL url new URL(myurl);HttpURLConnection conn (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod(GET);conn.setDoInput(true);// Starts the queryconn.connect();int response conn.getResponseCode();Log.d(DEBUG_TAG, The response is: response);is conn.getInputStream();// Convert the InputStream into a stringString contentAsString readIt(is, len);return contentAsString;// Makes sure that the InputStream is closed after the app is// finished using it.} finally {if (is ! null) {is.close();} }
}
注意getResponseCode()方法返回的是连接的状态码。该状态码可以用来获取连接的其它信息。状态码为200则表明连接成功。
将字节流转换为字符串
InputStream所读取的是字节数据。一旦获得InputStream对象通常需要将其解码或者转化为其它类型的数据。比如如果下载了一张图片则应该将字节流转码为图片
InputStream is null;
...
Bitmap bitmap BitmapFactory.decodeStream(is);
ImageView imageView (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
在上的示例中InputStream代表了Web页面的文本内容。下面的代码展示了如何将字节流转换为字符串
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {Reader reader null;reader new InputStreamReader(stream, UTF-8); char[] buffer new char[len];reader.read(buffer);return new String(buffer);
}