Android网络技术开发需要在AndroidManifest.xml文件中添加网络权限:
<!-- 添加网络权限 -->
<!--<manifest>在这里添加</manifest>-->
<uses-permission android:name="android.permission.INTERNET" />
一.HttpURLConnection
实例实现的功能:将百度首页以文本的形式返回到Android手机模拟器界面。
1.创建UI布局
<?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=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击发送请求(HttpURLConnection)"
android:id="@+id/Send_request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/Send_request">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response_text" />
</ScrollView>
</RelativeLayout>
2.在Activity里编写实现代码(注释写得很详细)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button sendRequest;
private TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = findViewById(R.id.Send_request);
responseText = findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
/**
* 点击按钮调用下面的网络请求方法
* @param v
*/
@Override
public void onClick(View v) {
if (v.getId()==R.id.Send_request){
sendRequestWithHttpUrlConnection();
}
}
/**
* 网络请求方法
*/
private void sendRequestWithHttpUrlConnection(){
//Android不允许在主线程中进行网络访问,所以要另起线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
/**
* BufferedReader的作用:
* 读取字符时会一次读取若干字符到缓冲区,
* 然后逐个返回给程序,
* 降低读取文件的次数。
*/
BufferedReader reader = null;
try{
/**
* 1.获取HttpURLConnection实例:
* new出一个URL对象,并传入目标的网络地址,
* 然后调用openConnection()即可。
*/
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
/**
* 2.设置HTTP请求所使用的方法:
* GET:从服务器获取数据;
* POST:提交数据给服务器。
*/
connection.setRequestMethod("GET");
/**
* 3.设置连接超时毫秒数
*/
connection.setConnectTimeout(8000);
/**
* 4.设置读取超时的毫秒数
*/
connection.setReadTimeout(8000);
/**
* 5.调用getInputStream()方法获取服务器返回的输入流
*/
InputStream in = connection.getInputStream();
/**
* 6.对输入流进行读取
*/
reader = new BufferedReader(new InputStreamReader(in));
/**
* 7.对读取的输入流进行处理
*/
StringBuffer response = new StringBuffer();
String line;
while ((line = reader.readLine())!=null){
response.append(line);
}
/**
* 8.调用显示文本的方法(自己写的方法)
*/
showResponse(response.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if (null!=reader){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (null!=connection){
//关闭HTTP连接
connection.disconnect();
}
}
}
}).start();
}
/**
* 显示获取的文本
* @param response
*/
private void showResponse(final String response){
/**
* 使用UI线程更新UI
*/
runOnUiThread(new Runnable() {
@Override
public void run() {
//进行UI操作,将结果显示到页面上
responseText.setText(response);
}
});
}
}
3.模拟器运行结果:
二.OkHttp
说明:
可以用出色的网络通信库OkHttp替代原生的HttpURLConnection(替代后代码量明显减少):
需要添加依赖:
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
添加依赖方法:
实例实现的功能:将百度首页以文本的形式返回到Android手机模拟器界面。
1.创建UI布局
<?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=".Main2Activity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击发送请求(OkHttp)"
android:id="@+id/Send_request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/Send_request">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response_text" />
</ScrollView>
</RelativeLayout>
2.在Activity里编写实现代码(注释写得很详细)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
private Button sendRequest;
private TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
sendRequest = findViewById(R.id.Send_request);
responseText = findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
/**
* 点击按钮调用下面的网络请求方法
* @param v
*/
@Override
public void onClick(View v) {
if (v.getId()==R.id.Send_request){
sendRequestWithOkHttp();
}
}
/**
* 网络请求方法
*/
private void sendRequestWithOkHttp(){
//Android不允许在主线程中进行网络访问,所以要另起线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
try{
/**
* 1.创建一个OkHttpClient实例。
*/
OkHttpClient client = new OkHttpClient();
/**
* 2.要发起HTTP请求,所以要创建一个Request对象,
* 通过url()方法设置目标网络地址。
*/
Request request = new Request.Builder().url("http://www.baidu.com").build();
/**
* 3.调用OkHttpClient的newCall()方法来创建一个Call对象,
* 并调用它的execute()方法来发送请求并获取服务器返回的数据,
* 其中Response对象就是服务器返回的数据。
*/
Response response = client.newCall(request).execute();
/**
*4.使用如下写法来得到返回的具体内容。
*/
String responseData = response.body().string();
/**
* 5.调用显示文本的方法(自己写的方法)
*/
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}finally {
}
}
}).start();
}
/**
* 显示获取的文本
* @param response
*/
private void showResponse(final String response){
/**
* 使用UI线程更新UI
*/
runOnUiThread(new Runnable() {
@Override
public void run() {
//进行UI操作,将结果显示到页面上
responseText.setText(response);
}
});
}
}
3.模拟器运行结果:
至此,用HttpURLConnection及OkHttp分别写的两个实例完成。