/**
*@author StormMaybin
*@Date 2016-09-1
*/
生命不息,奋斗不止!
WebView
对于,WebView 顾名思义,就是显示各种各样的网页的控件,用法也相当简单!
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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.stormmaybin.webviewtest.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</RelativeLayout>
MainActivity
package com.stormmaybin.webviewtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity
{
private WebView webView = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
//设置webView支持js脚本
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading (WebView view, String url)
{
//根据传入的参数加载新的网页
view.loadUrl(url);
//表示当前webView可以处理打开新网页的请求,不用借助系统浏览器
return true;
}
});
webView.loadUrl("http://www.baidu.com");
}
public void initView ()
{
webView = (WebView) findViewById(R.id.webView);
}
}
别往了申明访问网络权限
<uses-permission android:name="android.permission.INTERNET" />
这样一个WebView的例子就写好了
使用Http协议访问网络(HttpURLConnection)
Android 上发送HTTP请求方式一般有两种,HttpURLConnection和HttpClient,对于HttpURLConnection:
首先要获得一个HttpURLConnection的实例。
HttpURLConnection connection = (HttpURLConnection) new URL("url").openConnection();
这样就得到一个HttpURLConnection对象,接下来要设置HTTP请求的所使用的方法,方法有两个:”GET”和”POST”,GET表示希望从服务器端获得数据,POST表示往服务器端发送数据!
connection.setRequestMethod("GET");
除此之外,还有两个比较常用的HttpURLConnection方法,setConnectionTimeOut()连接超时设置和setReadTimeOut()读取超时,参数都是毫秒数。getInputStream()是获得服务器返回的输入流,disconnect()是关闭连接!
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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.stormmaybin.httpurlconnectiontest.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
</RelativeLayout>
MainActivity
package com.stormmaybin.httpurlconnectiontest;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
public static final int SHOW_RESPONSE = 0;
private Button sendRequest = null;
private TextView responseText = null;
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case SHOW_RESPONSE:
String response = (String)msg.obj;
//修改UI
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件对象
initView();
//设置Button监听事件
sendRequest.setOnClickListener(this);
}
public void initView ()
{
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
}
@Override
public void onClick(View v)
{
if (v.getId() == R.id.send_request)
{
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection()
{
//开启线程发起网络请求
new Thread(new Runnable()
{
@Override
public void run()
{
HttpURLConnection connection = null;
try
{
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
//一通设置
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//获取发武器返回的输入流
InputStream in = connection.getInputStream();
/**
* 开始对获取到的服务器输入流进行读取
*/
BufferedReader bufr = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufr.readLine() )!= null)
{
response.append(line);
}
Message msg = new Message();
msg.what = SHOW_RESPONSE;
//将服务器返回的结果存到Msg中
msg.obj = response.toString();
//发送消息
handler.sendMessage(msg);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
//关闭资源
if (connection != null)
{
connection.disconnect();
}
}
}
}).start();
}
}
权限申明
<uses-permission android:name="android.permission.INTERNET" />
使用Http协议访问网络(HttpClient)
HttpClient 是Apache 提供的一个HTTP网络访问接口,首先我们先要得到一个DefaultHttpClient 实例
HttpClient httpClient = new DefaultClient();
如果要发送一条GET请求,创建一个HttpGet对象,并传入目标的网络地址,然后调用HttpClient 的execute()方法
HttpGet httpGet = new HttpGet ("http://www.baidu.com");
httpClient.execute(httpGet);
发起一条POST
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","StormMa"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodeFormEnity enity = new UrlEncodeFormEnity(params, "utf-8");
httpPost.setEnity(enity);
httpClient.execute(httpPost);
执行完execute()方法之后会返回一个HttpResponse对象,这个对象包括了服务器返回的所有信息,如果状态码等于200说明请求响应成功了!
if (httpResponse.getStatusLine().getStatusCode == 200)
调用getEnity()方法获得一个HttpEnity对象,然后调用EnityUtils.toString()这个静态方法可以把HttpEnity转换成字符串
HttpEnity enity = httpResponse.getEnity();
//utf-8是为了返回中文不产生乱码
String response = EnityUtils.toString (enity, "utf-8");
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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.stormmaybin.httpclienttest.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
</RelativeLayout>
MainActivity
package com.stormmaybin.httpurlconnectiontest;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
public static final int SHOW_RESPONSE = 0;
private Button sendRequest = null;
private TextView responseText = null;
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case SHOW_RESPONSE:
String response = (String)msg.obj;
//修改UI
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件对象
initView();
//设置Button监听事件
sendRequest.setOnClickListener(this);
}
public void initView ()
{
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
}
@Override
public void onClick(View v)
{
if (v.getId() == R.id.send_request)
{
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection()
{
//开启线程发起网络请求
new Thread(new Runnable()
{
@Override
public void run()
{
HttpURLConnection connection = null;
try
{
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
//一通设置
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//获取发武器返回的输入流
InputStream in = connection.getInputStream();
/**
* 开始对获取到的服务器输入流进行读取
*/
BufferedReader bufr = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufr.readLine() )!= null)
{
response.append(line);
}
Message msg = new Message();
msg.what = SHOW_RESPONSE;
//将服务器返回的结果存到Msg中
msg.obj = response.toString();
//发送消息
handler.sendMessage(msg);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
//关闭资源
if (connection != null)
{
connection.disconnect();
}
}
}
}).start();
}
}