现在手机大部分功能基本上都依赖网络通讯,Android中的网络通讯支持JDK提供的ServiceScoket,Scoket的TCP/IP通信,支持JDK提供的Datagrampacket,DatagramScoket的UDP通信,当然也支持JDK提供的URL, URLConnection通信,除此之外Android内置了HttpClient,这样可以更加方便的发送Http请求和获取Http的响应。
对于Android中的TCP/IP和UDP协议通讯,是与Java中的完全相同的,大家可以参考文章《 java中的网络连接 》,在次不再赘述。《 java中的网络连接 》文章的内容比较多,大家可以参照目录查找相关内容(请原谅我当时年轻不会写博客……哈哈)。
好了,下面进入我们本节的主要内容URLConnection使用……
URLConnection
在使用URLConnection连接网络之前,我们应该先明白一点:在Android中,耗时的操作是不允许被放在主线程中的,网络连接由于要等待网络的响应,因此是耗时操作,不能放在主线程中。
我们通过一个例子来URLConnection。我们通过一个按钮连接服务器,并将服务器中的信息输出到我们的界面上。我们来看实例实现的整体步骤:
1. 定义一个布局文件,布局文件中我们使用到了ScrollView。 由于我们从服务中获得的数据可能比较多,我们的界面可能美版发完整的将数据显示出来,这时我们就是用ScrollView控件,ScrollView控件的使用有一个注意:ScrollView控件中只能定义一个子控件。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.networkdemo.UrlConnectionDemo">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="连接网络"/>
<TextView
android:id="@+id/textview_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
2. Activity中发送连接的请求并或的返回的数据。这儿离我们先贴出整体代码,在分步讲解。
public class UrlConnectionDemo extends Activity implements View.OnClickListener {
//常量
private static final int TYPE_CONNECT = 0x9900;
private Button mButton;
private TextView mTextViewContent;
//开启一个UrlConnnetion的连接
private URLConnection mConnnection;
//创建一个主线程的Handler
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TYPE_CONNECT:
String content = (String) msg.obj;
mTextViewContent.setText(content);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_connection_demo);
mButton = (Button) findViewById(R.id.button_connect);
mTextViewContent = (TextView) findViewById(R.id.textview_content);
mButton.setOnClickListener(this);//点击事件
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_connect:
connectServelet();
break;
default:
break;
}
}
private void connectServelet() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://www.360.com/");//连接的网址
mConnnection = url.openConnection();//获得连接
InputStream is = mConnnection.getInputStream();//获得输出流
//将输出流一顿封装
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
StringBuffer buffer = new StringBuffer();
while (line != null) {
Log.d("data", "" + line);
buffer.append(line);
line = br.readLine();
}
br.close();
is.close();
//定义子线程给主线程发送的消息
Message msg = handler.obtainMessage();
msg.what = TYPE_CONNECT;
msg.obj = buffer.toString().trim();
handler.sendMessage(msg);//发送消息
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
在Android中不允许将网络连接耗时操作放在主线程中,我们只能再开一个子线程。但是主线程又不允许子线程修改界面,这是我们就需要使用Handler来实现,不懂得可以先看《 Android中的多线程 》这篇文章了解Handler的使用。这里我么不再具体讲述,只介绍URLConnection部分.
- 创建一个URL对象。URL对象代表统一资源定位器,它指向互联网中的“资源”。也就是我们创建一个指向我们访问地址的“指针”。
- 通过URL对象获得URLConnectin连接。
- 通过连接获得输出流对象。
- 将输出流封装。
//创建一个指向服务器的地址。
URL url = new URL("http://www.360.com/");
mConnnection =url.openConnection();//获得连接
InputStream is = mConnnection.getInputStream();//获得输出流
//……封装部分省略
结果演示: