现在的位置: 首页 > 综合 > 正文

14天学会安卓开发(第十天)Android网络与通讯

2014年09月05日 ⁄ 综合 ⁄ 共 11297字 ⁄ 字号 评论关闭

【原文:http://blog.csdn.net/corder_raine/article/details/8317306

14天学会安卓开发  
作者:神秘的N (英文名  corder_raine)

联系方式:369428455(反馈)
交流群:284552167(示例,原文档下载)

版权为作者所有,如有转载请注明出处
目录 
           



第十天.Android网络与通信... 100
10.1  Android网络通讯介绍... 100
10.1.1 网络通讯技术... 100
10.2  Java.net 101
10.2.2主Activity. 101
10.2.3 直接获取数据... 102
10.2.4 以Get方式上传参数... 103
10.2.5 以Post方式上传参数... 103
10.3  ApacheHttpClient 105
10.3.1 使用HttpClient:主Activity. 105
10.3.2 HttpClient:HttpGet 106
10.3.3 HttpClient:HttpPost 107
10.4  装载并显示Web网页... 108
10.4.1 用线程刷新网页显示... 108
10.4.2 装载网页并显示... 109
10.5  Socket编程复习... 110



第十天.Android网络与通信
10.1 Android网络通讯介绍
    10.1.1 网络通讯技术

Ø  Java.net
Ø  Apache HttpClient
Ø  Socket技术
Ø  装载网页
Ø  WiFi技术
Ø  Bluetooth蓝牙

10.2 Java.net
10.2.2Activity

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
publicclass

Activity01 extendsActivity{
       publicvoid
onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main)       
              Buttonbutton_http
= (Button) findViewById(R.id.Button_HTTP);
              /*监听button的事件信息
*/
              button_http.setOnClickListener(newButton.OnClickListener()
{
                     publicvoid
onClick(View v){
                     /*新建一个Intent对象
*/
                     Intentintent
= new Intent();
                     /*指定intent要启动的类
*/
                     intent.setClass(Activity01.this,Activity02.class);
                     /*启动一个新的Activity*/
                     startActivity(intent);
                     /*关闭当前的Activity*/
                     Activity01.this.finish();
                     }
              });
**   Activity02是直接获取数据的demo!
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
Button
button_Get = (Button)findViewById(R.id.Button_Get);
              /*监听button的事件信息
*/
              button_Get.setOnClickListener(newButton.OnClickListener()
{
                     publicvoid
onClick(View v)
                     {
                            /*新建一个Intent对象
*/
                            Intentintent
= new Intent();
                            /*指定intent要启动的类
*/
                            intent.setClass(Activity01.this,Activity03.class);
                            /*启动一个新的Activity*/
                            startActivity(intent);
                            /*关闭当前的Activity*/
                            Activity01.this.finish();
                     }
              });
**   Activity03是以Get方式上传参数的demo!
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
Button
button_Post = (Button)findViewById(R.id.Button_Post);
              /*监听button的事件信息
*/
              button_Post.setOnClickListener(newButton.OnClickListener()
{
                     publicvoid
onClick(View v)
                     {
                            /*新建一个Intent对象
*/
                            Intentintent
= new Intent();
                            /*指定intent要启动的类
*/
                            intent.setClass(Activity01.this,Activity04.class);
                            /*启动一个新的Activity*/
                            startActivity(intent);
                            /*关闭当前的Activity*/
                            Activity01.this.finish();
                     }
              });
       }
}//结束Activity1类
**   Activity04是以Post方式上传参数的demo!

10.2.3 直接获取数据

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
//http地址
//获得的数据
String
resultData =
"";
URLurl =
null;
//构造一个URL对象
url
=
newURL(httpUrl);
       //使用HttpURLConnection打开连接
HttpURLConnection
urlConn =(HttpURLConnection) url.openConnection();
//得到读取的内容(流)
InputStreamReader
in = newInputStreamReader(urlConn.getInputStream());
//
为输出创建BufferedReader
BufferedReader
buffer = newBufferedReader(in);
String
inputLine =
null;
//使用循环来读取获得的数据
while(((inputLine
= buffer.readLine())!=
null)){
       resultData+=
inputLine +
"";
}
**   研究HttpURLConnectionDemo工程(Activity02.java)
**  serverip要换成真实IP,不能用localhost127.0.0.1  


10.2.4 Get方式上传参数

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
       URLurl
=
newURL(httpUrl);
       //使用HttpURLConnection打开连接
       HttpURLConnectionurlConn
= (HttpURLConnection) url.openConnection();
       //得到读取的内容(流)
       InputStreamReaderin
=
newInputStreamReader(urlConn.getInputStream());
       //为输出创建BufferedReader
       BufferedReaderbuffer
=
newBufferedReader(in);
       StringinputLine
=
null;
       //使用循环来读取获得的数据
       while(((inputLine
= buffer.readLine()) !=
null)){
resultData += inputLine +
"";
       //关闭InputStreamReader
       in.close();
       //关闭http连接
       urlConn.disconnect();
**   研究HttpURLConnectionDemo工程(Activity03.java)
**  serverip要换成真实IP,不能用localhost127.0.0.1


10.2.5 Post方式上传参数

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
URL
url =
newURL(httpUrl);        
HttpURLConnection
urlConn = (HttpURLConnection)url.openConnection();
//因为这个是post请求,设立需要设置为true
urlConn.setDoOutput(true);urlConn.setDoInput(true);
urlConn.setRequestMethod("POST");         //
设置以POST方式
urlConn.setUseCaches(false);                  //
Post 请求不能使用缓存
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConn.connect();
DataOutputStream
out = newDataOutputStream(urlConn.getOutputStream());
String
content =
"par="+URLEncoder.encode("ABCDEFG","gb2312");//要上传的参数
out.writeBytes(content);                  //将要上传的内容写入流中
out.flush();       
out.close();
//获取数据
BufferedReader
reader = newBufferedReader(
newInputStreamReader(urlConn.getInputStream()));
String
inputLine =
null;
while(((inputLine
= reader.readLine())!=
null)){resultData
+= inputLine +
"";} 
       reader.close();urlConn.disconnect();
**   研究HttpURLConnectionDemo工程(Activity03.java)
**  serverip要换成真实IP,不能用localhost127.0.0.1       
       


main.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="通过下面的按钮进行不同方式的连接"/>
        <Button
                android:id="@+id/Button_HTTP"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="直接获取数据"/>
        <Button
                android:id="@+id/Button_Get"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="以GET方式传递数据"/>
        <Button
                android:id="@+id/Button_Post"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="以POST方式传递数据"/>
</LinearLayout>


AndroidManifest.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
      package="com.lxt008"
      android:versionCode="1"
      android:versionName="1.0">
    <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
        <activityandroid:name=".Activity01"
                  android:label="@string/app_name">
            <intent-filter>
                <actionandroid:name="android.intent.action.MAIN"/>
                <categoryandroid:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
                <activityandroid:name="Activity02"></activity>
                <activityandroid:name="Activity03"></activity>
                <activityandroid:name="Activity04"></activity>
    </application>
        <uses-permissionandroid:name="android.permission.INTERNET"/>
    <uses-sdkandroid:minSdkVersion=“7"
/>
</manifest>


10.3 ApacheHttpClient   
   10.3.1 使用HttpClient:Activity

1
2
3
4
5
6
7
8
Button
button_Get = (Button)findViewById(R.id.Button_Get);
button_Get.setOnClickListener(newButton.OnClickListener()
{
       publicvoid
onClick(View v){
              Intentintent
=
newIntent();
/*
新建一个Intent对象 */
              /*指定intent要启动的类
*/
              intent.setClass(Activity01.this,Activity02.class);                 
              startActivity(intent);/*
启动一个新的Activity*/                      Activity01.this.finish();/* 关闭当前的Activity*/
}
              });


1
2
3
4
5
6
7
8
9
Button
button_Post = (Button)findViewById(R.id.Button_Post);
button_Post.setOnClickListener(newButton.OnClickListener()
{
       publicvoid
onClick(View v){
              Intentintent
=
newIntent();
              /*指定intent要启动的类
*/
              intent.setClass(Activity01.this,Activity03.class);
              startActivity(intent);                                     
Activity01.
this.finish();}
              });  
       }
**   研究ApacheHttpClientDemo工程(Activity01.java)
**  serverip要换成真实IP,不能用localhost127.0.0.1


10.3.2 HttpClient:HttpGet

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
//HttpGet连接对象
HttpGet
httpRequest = newHttpGet(httpUrl);
//取得HttpClient对象     
HttpClient
httpclient = newDefaultHttpClient(); 
//请求HttpClient,取得HttpResponse
HttpResponse
httpResponse = httpclient.execute(httpRequest);
//请求成功
if(httpResponse.getStatusLine().getStatusCode()==
HttpStatus.SC_OK){
       //取得返回的字符串
       StringstrResult
= EntityUtils.toString(httpResponse.getEntity());
       mTextView.setText(strResult);
}
else{
       mTextView.setText("请求错误!");
[align=left]}
**   研究ApacheHttpClientDemo工程(Activity02.java)
**  serverip要换成真实IP,不能用localhost127.0.0.1


10.3.3 HttpClient:HttpPost

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
//HttpPost连接对象
HttpPost
httpRequest = newHttpPost(httpUrl);
//使用NameValuePair来保存要传递的Post参数
List
params = newArrayList();
//添加要传递的参数
params.add(newBasicNameValuePair("par","HttpClient_android_Post"));
//设置字符集
HttpEntity
httpentity = newUrlEncodedFormEntity(params,
"gb2312");
//请求httpRequest
httpRequest.setEntity(httpentity);
//取得默认的HttpClient
HttpClient
httpclient = newDefaultHttpClient();
//取得HttpResponse
HttpResponse
httpResponse =httpclient.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode()
== HttpStatus.SC_OK){
       StringstrResult
= EntityUtils.toString(httpResponse.getEntity());}
**   研究ApacheHttpClientDemo工程(Activity03.java)
**  serverip要换成真实IP,不能用localhost127.0.0.1


10.4 装载并显示Web网页
  10.4.1 用线程刷新网页显示

01
02
03
04
05
06
07
08
09
10
publicvoid

onCreate(BundlesavedInstanceState){
newThread(mRunnable).start();
//开启线程
}
       //刷新网页显示
       privatevoid
refresh(){       
              URLurl
=
newURL("http://192.168.1.110:8080/date.jsp");
              HttpURLConnectionurlConn
= (HttpURLConnection) url.openConnection();
              InputStreamReaderin
=
newInputStreamReader(urlConn.getInputStream());
              BufferedReaderbuffer
=
newBufferedReader(in);
              StringinputLine
=
null;
              //使用循环来读取获得的数据
//关闭InputStreamReader// 设置显示取得的内容 }
}
01
02
03
04
05
06
07
08
09
10
privateRunnable
mRunnable = newRunnable()  {
       publicvoid
run()  {
             while(true)
{         Thread.sleep(
5*
1000);
                 //发送消息
                 mHandler.sendMessage(mHandler.obtainMessage()); 
};
         Handler
mHandler =
newHandler()
{
           publicvoid

handleMessage(Message msg)  {
             super.handleMessage(msg);
             refresh();
           }
};
**   研究HttpURLConnectionRefresh工程


10.4.2 装载网页并显示

1
2
3
4
5
6
7
8
WebView
webView = (WebView)findViewById(R.id.webview);
String
html =
"Hello
lxt008!!!"
;
//装载页面,你可以换成URL地址。
webView.loadDataWithBaseURL("Demo",html,"text/html","utf-8",null);
//设置支持JS
webView.getSettings().setJavaScriptEnabled(true);
//设置浏览器客户端
webView.setWebChromeClient(newWebChromeClient());


10.5 Socket编程复习

Ø    以前课程中学过Socket编程。
Ø  研究SocketDemo以复习巩固Socket在Android中的使用。


示例下载

抱歉!评论已关闭.