Android——网络编程

Android——网络编程

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

WebView的用法

提供了一个 WebView 控件,借助它我们就可以在自己的应用程序里嵌入一个浏览器,从而非常轻松地展示各种各样的网页。 在布局文件中加入一个WebView控件。

<WebView
    android:id="@+id/web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

设置一个id,并让他充满整个屏幕。

public class MainActivity extends Activity {
	private WebView webView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		webView = (WebView) findViewById(R.id.web_view);
		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");
	}
}

WebView 的 getSettings()方法可以去设置一些浏览器的属性 ,调用了 setJavaScriptEnabled()方法来让 WebView 支持 JavaScript 脚本。 调用 WebView 的 setWebViewClient()方法,并传入了 WebViewClient 的匿名类作为参数,然后重写了 shouldOverrideUrlLoading()方法。这就表明当需要从一个网页跳转到另一个网页时,我们希望目标网页仍然在当前 WebView 中显示,而不是打开系统浏览器。调用 WebView 的 loadUrl()方法,并将网址传入,即可展示相应网页的内容

由于使用到网络内容,而访问网络是需要声明权限的,因此我们还需要修改AndroidManifest.xml 文件,并加入权限声明。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.webviewtest"
    android:versionCode="1"
    android:versionName="1.0" >
<!-- ···················  -->
    <uses-permission android:name="android.permission.INTERNET" />
<!-- ···················  -->
</manifest>

使用HTTP协议访问网络

工作原理,就是客户端向服务器发出一条HTTP 请求,服务器收到请求之后返回一些数据给客户端,然后客户端再对这些数据进行解析和处理。

在Android上发送HTTP请求的方式一般有两种,HttpURLConnection 和 HttpClient(接口)。

  1. 使用HttpURLConnection

获取实例:只需要New出一个URL对象,并传入目标的网路地址。然后调用一下openConnection()方法即可 。

URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

设置请求的方式GET / POST

connection.setRequestMethod("GET");

可以进行一些自由的定制,如设置连接超时,读取超时的毫秒数等等。

connection.setConnectTimeout(8000);    // 连接超时时间
connection.setReadTimeout(8000);    // 读取超时时间

获取服务器返回的输入流

InputStream in = connection.getInputStream();

关闭HTTP连接

connection.disconnect();
实例:
	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);
					connection.setDoInput(true);
					connection.setDoOutput(true);
					InputStream in = connection.getInputStream();
					// 下面对获取到的输入流进行读取
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);
					}
					Message message = new Message();
					message.what = SHOW_RESPONSE;
					// 将服务器返回的结果存放到Message中
					message.obj = response.toString();
					handler.sendMessage(message);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}).start();
	}
  1. 使用 HttpClient (接口)

它可以完成和 HttpURLConnection 几乎一模一样的效果,但两者之间的用法却有较大的差别。HttpClient ()是一个接口,无法创建它的实例,通常会创建一个DefaultHttpClient 的实例 。

HttpClient httpClient = new DefaultHttpClient();

要发起一条GET请求,可以创建一个HttpGet对象,并传入目标网络地址。然后调用HttpClient 的 execute()方法即可 。

HttpGet httpGet = new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);

发起Post请求会比较复杂。要创建一个HttpPost对象,并传入目标网络地址。

HttpPost httpPost = new HttpPost("http://www.baidu.com");

然后通过NameValuePair集合来存放待提交的参数,并将集合传入到一个UrlEncodedFormEntity 中,然后调用 HttpPost 的 setEntity()方法将构建好的 UrlEncodedFormEntity传入,

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);

太难了 不写了!!!!!!!!!!!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值