Android开发学习之路--网络编程之初体验

一般手机都是需要上网的,一般我们的浏览器就是个webview。这里简单实现下下功能,先编写Android的layout布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:layout_margin="10dp"
android:padding="10dp"
tools:context="com.example.jared.webviewstudy.MainActivity"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/netAddress"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/openNetAddress"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="0"
android:text="Open"
android:textAllCaps="false"/>
</LinearLayout> <WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>

这里主要是一个EditText用来输入网址,然后一个Button用来打开网页,webView用来呈现网页。编写代码如下:

package com.example.jared.webviewstudy;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText; public class MainActivity extends AppCompatActivity { private WebView myWebView;
private EditText networkAddr;
private Button openNetwork; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); networkAddr = (EditText)findViewById(R.id.netAddress);
myWebView = (WebView)findViewById(R.id.webView); openNetwork = (Button)findViewById(R.id.openNetAddress);
openNetwork.setOnClickListener(new myOnClickListener());
} class myOnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
String networkAddress = networkAddr.getText().toString();
myWebView.loadUrl("http://"+networkAddress);
}
}
}

还有就是权限问题了:

    <uses-permission android:name="android.permission.INTERNET"/>

这里通过setWebViewClient方法,实例化一个WebViewClient,loadurl实现网页的加载。运行看下效果:

Android开发学习之路--网络编程之初体验 
 Android开发学习之路--网络编程之初体验

这里打开了百度和我的博客的地址,界面略难看,勉强看看了。

一般网络编程都是通过http的,下面就来实现下,首先是HttpURLConnection,这个一般是google官方提供的,还有一个HttpClient,本来有的,现在api23也没有了,需要自己加载进来。

先使用HttpURLConnection和HttpClient吧,新建工程,编写layout代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
android:layout_margin="10dp"
tools:context="com.example.jared.httpurlconnectionstudy.MainActivity"> <Button
android:id="@+id/sendRequest"
android:text="发送请求"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <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>

这里主要就是一个按钮获取数据,然后http请求的数据通过ScrollView可以滑动浏览更多的信息,然后把获取到的信息显示在TextView里面。

编写MainActivity,里面有实现了HttpURLConnection和HttpClient:

package com.example.jared.httpurlconnectionstudy;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; public class MainActivity extends AppCompatActivity { private static final int SHOW_RESPONSE = 1; private Button sendRequestBtn;
private TextView responseView; private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String responseContent = (String)msg.obj;
responseView.setText(responseContent);
break;
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide(); setContentView(R.layout.activity_main); responseView = (TextView)findViewById(R.id.response);
sendRequestBtn = (Button)findViewById(R.id.sendRequest);
sendRequestBtn.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sendRequest:
String url = "http://www.baidu.com";
//sendRequestWithHttpURLConnection(url);
sendRequestWithHttpClient(url);
break;
default:
break;
}
}
} private void sendRequestWithHttpClient(final String url) {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8"); Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
mHandler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} private void sendRequestWithHttpURLConnection(final String url) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL mUrl = new URL(url);
connection = (HttpURLConnection)mUrl.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
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.obj = response.toString();
mHandler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}

这里的HttpClient需要在\sdk\platforms\android-23\optional下倒入包到工程目录的libs下面,然后

在build.gradle下面添加

// Apache Http
android {
useLibrary 'org.apache.http.legacy'
}
// Header
dependencies {
compile "org.apache.httpcomponents:httpcore:4.3.2"
}

这样HttpClient就可以使用了,关于加载别的库,也基本上类似了。

运行效果如下:

Android开发学习之路--网络编程之初体验

关于Http常用的框架有android-async-http,下面就使用下。jar包可以从官网下载:http://loopj.com/android-async-http/。此外还得下载一个httpclient的jar包:http://mvnrepository.com/artifact/cz.msebera.android/httpclient/4.4.1.1

修改build.gradle如下:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile files('libs/android-async-http-1.4.9.jar')
compile files('libs/httpclient-4.4.1.1.jar')
}

这里把两个包都放在了libs的目录下。切换到project目录,如下图:

Android开发学习之路--网络编程之初体验

修改MainActivity代码,添加sendRequestWithAsyncHttpClinet方法如下:

private void sendRequestWithAsyncHttpClient(String url) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
try {
String response = new String(bytes, 0, bytes.length, "UTF-8");
responseView.setText(response);
}catch (Exception e) {
e.printStackTrace();
}
} @Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { }
});
}

运行可以得到我们一样的效果。AsyncHttpClient很方便地可以使用起来了,比起上面一大堆代码简单了不少。这里通过一个get方法,然后再onSuccess方法中把获取到的数据转为String显示在text就ok了。

关于网络编程的webview和http就基本学到这里了。在此还要谢谢朋友的提醒,光学基础,实际项目会用到很多框架的,需要去熟悉,这里继续慢慢学。

上一篇:Ceph学习笔记(3)- Monitor


下一篇:配置linux-Fedora系统下iptables防火墙