目录
1、使用Android的HttpURLConnection步骤
4)调用getInputStream()方法获取返回的输入流
一、使用HttpURLConnection
1、使用Android的HttpURLConnection步骤
1)获取HttpURLConnection实例
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HtppURLConnection) url.openConnection();2)设置HTTP请求使用的方法
connection.setRequestMethod("GET");3)定制HTTP请求,如连接超时、读取超时的毫秒数
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);4)调用getInputStream()方法获取返回的输入流
InputStream in = connection.getInputStream();5)关闭HTTP连接
connection.disconnect();2、实例
新建NetWorkTest项目,
修改activity_main.xml代码,如下:
<?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>修改MainActivity的代码,如下:
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("https://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);
            }
        });
    }
}最后声明网络权限,修改AndroidManifest.xml代码,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.INTERNET" />
................效果如下:
这是百度浏览器的HTML代码。

如何将数据提交给服务器?
如我们想向服务器提交用户名和密码,代码如下:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream);
out.writeBytes("username=admin&password=123456");二、使用OkHttp
以上方法是原生方法,接下来使用的OkHttp是比较出色的网络通信库。
在使用之前,需要现在项目中添加OkHttp库的依赖,修改app/build.gradle文件,在dependencies闭包中添加以下内容。
dependencies {
    ...........
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'1、使用OkHttpClient的步骤
1)创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();2)创建Request对象
Request request = new Request.Builder().build();
3)设置目标网络的URL地址
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .build();4)发送请求获取服务器返回的数据
Response response = client.newCall(request).execute();5)获得返回的具体内容
String responseData = response.body().string();如果发起一条POST请求,需要先构建一个RequestBody对象来存放待提交的参数,如下:
RequestBody requestBody = new FormBody.Builder()
            .add("username","admin")
            .add("password","123456")
            .build();然后再Request.Builder中调用post()方法,将RequestBody对象传入:
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .post(requestBody)
        .build();下面的操作和GET请求一样,调用execute()方法来发送请求并获取服务器返回的数据。
2、实例
在上面的项目中修改。
布局部分不动,修改MainActivity代码,如下:
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();
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://www.bjtu.edu.cn")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.bjtu.edu.cn");
                    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);
            }
        });
    }
}









