Android基础总结(9)——网络技术

时间:2021-07-02 04:04:05

  这里主要讲的是如何在手机端使用HTTP协议和服务器端进行网络交互,并对服务器返回的数据进行解析,这也是Android最常使用到的网络技术了。

1、WebView的用法

  Android提供的WebView控件可以帮助我们在自己的应用程序中嵌入一个浏览器,从而非常轻松的展示各种各样的网页。下面是一个简单的示例:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>
 public class MainActivity extends Activity {

     private WebView webView ;

     @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view); webView = (WebView) findViewById(R.layout.web_view) ;
//调用getSettings()方法可以去设置浏览器的属性,我们这里只是调用
//setJavaScriptEnabled(true)方法来设置WebView支持TavaScript脚本
webView.getSettings().setJavaScriptEnabled(true);
/*
* 调用setWebViewClient()时我们传入了一个WebViewClient对象
* 这样做的功能是当需要从一个网页跳转到另一个网页时,我们希望目标
* 网页仍然在当前网页上显示,而不是打开系统浏览器
*/
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.baidu.com");
}
}

2、使用HttpURLConnection访问网络

  使用HttpURLConnection访问网络的方式很简单,具体按以下步骤执行就可以了:

    1. 获取HttpURLConnection对象,一般我们只需要new一个URL对象,并传入目标网络地址,然后调用一下openConnection()方法即可
       URL url = new URL("http://www.baidu.com") ;
      HttpURLConnection con = (HttpURLConnection) url.openConnection() ;
    2. 获取HttpURLConnection对象之后,设置HTTP请求所使用的方法。常用的方法有两种:GET或POST。GET表示希望从服务器那里获取数据,POST则表示希望提交数据给服务器。
       con.setRequestMethod("GET");
    3. 接下来可以进行一些*的设置,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等
       con.setConnectTimeout(8000);
      con.setReadTimeout(8000);
    4. 之后我们调用getInputStream()方法得到从服务器返回的输入流,然后从里面读取数据。注意,服务器返回给我们的HTML代码
       InputStream in = con.getInputStream() ;
      BufferedReader reader = new BufferedReader(new InputStreamReader(in)) ;
      StringBuilder response = new StringBuilder() ;
      String line ;
      while((line = reader.readLine()) != null){
      response.append(line) ;
      }
    5. 最后,使用完之后,我们要记得关闭连接资源
       con.disconnect();

  下面的代码是在界面上设置了一个按钮和一个编辑框,通过点击按钮,手机访问“http://www.baidu.com”网页,并将返回的数据显示在文本框中。布局代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Request" /> <ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.61" >
<EditText
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textMultiLine" >
</EditText>
</ScrollView>
</LinearLayout>

  Activity代码如下:

 public class MainActivity extends Activity implements OnClickListener{

     private static final int SHOW_RESPONSE = 0 ;
private Button sendResquest ;
private EditText responseText ; private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case SHOW_RESPONSE :
String response = (String)msg.obj ;
//显示结果
responseText.setText(response);
}
}
} ; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout); sendResquest = (Button) findViewById(R.id.button) ;
responseText = (EditText) findViewById(R.id.response_text) ;
sendResquest.setOnClickListener(this) ;
} @Override
public void onClick(View v) {
if(v.getId() == R.id.button){
sendRequestWithHttpURLConnection() ;
}
} private void sendRequestWithHttpURLConnection() {
//开启线程发起网络
new Thread(new Runnable(){ @Override
public void run() {
HttpURLConnection con = null ;
try {
URL url = new URL("http://www.baidu.com") ;
con = (HttpURLConnection) url.openConnection() ;
con.setRequestMethod("GET");
con.setConnectTimeout(8000);
con.setReadTimeout(8000);
InputStream in = con.getInputStream() ;
BufferedReader reader = new BufferedReader(new InputStreamReader(in)) ;
StringBuilder response = new StringBuilder() ;
String line ;
while((line = reader.readLine()) != null){
response.append(line) ;
} Message msg = new Message() ;
msg.what = SHOW_RESPONSE ;
msg.obj = response.toString() ;
handler.sendMessage(msg) ; } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(con != null){
con.disconnect();
}
}
}
}).start();
}
}

        Android基础总结(9)——网络技术

3、使用HttpClient

  访问网络,除了用上面的HttpURLConnection之外,我们还可以用HttpClient来访问http网页资源。HttpClient可以完成过和HttpURLConnection几乎一模一样的功能。具体用法如下:

    1. 获取HttpClient的实例,但是HttpClient是一个接口,我们通常是创建一个DefaultHttpClient对象
       HttpClient httpClient = new DefaultHttpClient() ;
    2. 接下来如果要发起一条GET请求,则我们需要创建一个HttpGet对象,并传入目标网络的地址,然后调用HttpClient的execute()方法就可以获得服务器的响应HttpResponse 对象
       HttpGet httpGet = new HttpGet("http://www.baidu.com") ;
      HttpResponse httpResponse = httpClient.execute(httpGet) ;

      如果是要发起一条POST请求,我们需要和创建一个HttpPost对象,并传入目标网络地址,然后通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入,然后调用HttpClient的execute()方法就可以获得服务器的响应HttpResponse 对象

       HttpPost httpPost = new HttpPost("http://www.baidu.com") ;
      List<NameValuePair> params = new ArrayList<NameValuePair>() ;
      params.add(new BasicNameValuePair("username","admin")) ;
      params.add(new BasicNameValuePair("password","123456")) ;
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8");
      httpPost.setEntity(entity);
      HttpResponse httpResponse = httpClient.execute(httpPost) ;
    3. 得到HttpResponse 对象之后,服务器所返回的信息就全部都包含在这里了。通常情况下我们都会先取出服务器返回的状态码,如果等于200就说明请求和相应都成功了,然后我们就提取HttpEntity实例,然后将这个实例转化为String即可
       if(httpResponse.getStatusLine().getStatusCode() == 200){
      //请求和相应都成功了
      HttpEntity entity = httpResponse.getEntity() ;
      String response = EntityUtils.toString(entity,"utf-8") ; Message msg = new Message() ;
      msg.what = SHOW_RESPONSE ;
      msg.obj = response.toString() ;
      handler.sendMessage(msg) ;
      }