Android 浅谈访问网络
最近开始对Android一些基础性的知识总结一下,并且也锻炼一下自己的写作能力,希望自己能够好好的学习技术,静下来总结。
谈到Android 使用HTTP协议访问网络,其实简单的理解就是客户端向服务端发出一条HTTP请求,服务器会收到请求之后会返回一些数据给客户端,然后客户端再对这些数据进行解析和处理。
在Android上发送HTTP请求一般会有两种形式:HttpURLClient和HttpClient,不过由于HttpClient存在API数量多,使用比较麻烦,扩展困难的缺点,在Android 6.0 系统中,HttpClient的功能被完全移除了。因此官方现在简易使用HttpURLConnection。
接下来简单的介绍一下HttpURLConnection
1.1 HttpURLConnection
来个简单的例子:
布局文件比较简单
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<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_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
下面是主要逻辑代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@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;
BufferedReader reader = 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();
// 下面对获取到的输入流进行读取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
showResponse(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
});
}
}
在得到HttpURLClientConnection的实例之后,我们可以设置一下HTTP请求所使用的方法。常常使用的方法就是GET和POST。GET表示希望从服务器哪里获取数据,而POST则希望提交给服务器。
这里需要注意的是最后调disconnect()方法是将这个HTTP链接关闭。
还有必须要添加网络权限
package="com.example.networktest">
<uses-permission android:name="android.permission.INTERNET" />
<application
当然我们并不是只能使用HttpURLClient,在开源盛世的今天OKHttp无疑也是一个很出色的访问方式;下来我们简单的介绍一下OKHttp
1.2 OKHttp
首先需要添加OKHttp库的依赖,编辑app/buile.gradle文件,在dependencies闭包中添加如下内容:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
由于OKHttp封装的比较完善,用法也比较简单直接上例子(推荐如果有时间我们还是应该深入的学习一下OKHttp源码,分析设计的原因)
/**
* Description:
* Copyright : Copyright (c) 2016
* Author : yangfang
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
...
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
// 指定访问的服务器地址是电脑本机
.url("http://10.0.2.2/get_data.json")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseJSONWithGSON(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
...
}
好了,HttpURLConnection和OkHttp的基本用法基本描述完了,接下来我们应该考虑服务端传回来的数据我们如何解析的问题,请参考下一篇浅析网络数据解析。