您的位置:首页 > 理论基础 > 计算机网络

连接网络(Connecting to the Network)

2014-12-24 14:44 344 查看

连接网络(Connecting to the Network)

文章位置:Develop>>Training>>Performing Network Operations>>Connecting to the Network
这节课告诉你怎么做一个可以连接网络的简单程序。它介绍了一些你在创建应用甚至是最简单的联网应用时应该遵循最好的实践经验。
注意在这节课所描述的网络操作,你的应用清单文件必须包括以下权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

选择一个HTTP Client

大多数联网安卓app使用HTTP发送和接收数据。安卓包括两个HTTP客户端:
HttpURLConnection和阿帕奇HttpClient。都支持HTTPS,流的上传和下载,配置超时时间,IPv6,和连接池。

在Gingerbread(姜饼 2.3)及以上我们推荐使用HttpURLConnection。更多关于这个主题的讨论,看公布的博客Android's
HTTP Clients.

检查网络连接

在你的app尝试连接网络之前,应该用getActiveNetworkInfo()和isConnected()检查是否网络连接可用。

记住,设备可能不在网络范围内,或者用户可能同时是关闭了Wi-Fi和手机数据传输。更多关于这个问题的讨论看Managin 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
}
...
}


在单独线程执行网络操作

网络操作会导致不可预知的延迟。为了更好的客户体验通常网络操作会放在UI线程以外单独的线程中。更多关于这个问题的讨论,见博客多线程执行(Multithreading For Performance).

在下面的部分,myClickHandler()方法调用new DownloadWebpageTask().execute(stringUrl)。
DownloadWebpageTask类是 AsyncTask的子类。DownloadWebpageTask实现了AsyncTask以下方法:
*doInBackground()执行方法downloadUrl()。将网页URL作为参数传递。方法downloadUrl()取回并处理网页内容。完成后传回结果字符串。
*onPostExecute()获取返回的字符串并展示在UI上。
public class HttpExampleActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;

@Override
public 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 UI's 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 AsyncTask's onPostExecute method.
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected 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.
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
...
}
上述事件的顺序如下:
1.当用户点击按钮调用myClickHandler(),这个app传递指定的URL给AsyncTask子类DownloadWebpageTask.
2.AsyncTask方法doInBackground()调用downloadUrl方法。
3.downloadUrl()方法获取一个URL字符串作为参数并且用这个字符串创建一个URL对象。
4.URL对象用来建立一个HttpURLConnection。
5.一旦连接被建立,HttpURLConnection对象通过InputStream获取网页内容。
6.InputStream传递到readIt()方法,将流转换为字符串。
7.最后,AsyncTask的onPostExecute()方法在activity的UI中展示字符串。

连接和下载数据

在新建的线程中执行网络处理,你可以用HttpURLConnection来执行一个GET请求下载你的数据。
在调用connect()之后你可以通过getInputStream得到一个InputStream。

下面的部分,doInBackground()方法调用downloadUrl方法。downloadUrl方法得到传入的URL并用HttpURLConnection连接到网络。
一旦连接建立,app用getInputStream方法将数据转化为InputStream。
// Given a UR
4000
L, 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 query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();

// Convert the InputStream into a string
String 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包含的是网页的文本。这就是怎样将InputStream转换为字符串的例子,activity可以将字符串展示在UI上:
// 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 安卓 app network url