Android中的网络编程:HTTP与HTTPS请求

技术深度剖析 2019-05-03 ⋅ 32 阅读

在Android应用程序中,经常需要与服务器进行数据交互。而与服务器进行数据交互的方式主要包括HTTP和HTTPS请求。本文将介绍Android中的网络编程以及如何使用HTTP和HTTPS请求来获取数据。

一、HTTP请求

HTTP(Hypertext Transfer Protocol)是一种用于传输超文本的协议。在Android中,可以使用HttpURLConnection或HttpClient来发送HTTP请求。

1.1 HttpURLConnection

HttpURLConnection是Android中自带的类,用于发送HTTP请求。以下是一个使用HttpURLConnection发送GET请求的示例:

try {
    URL url = new URL("http://www.example.com/user?id=1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");

    int responseCode = connection.getResponseCode();
    if (responseCode == HttpsURLConnection.HTTP_OK) {
        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder response = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }

        bufferedReader.close();
        connection.disconnect();

        // 将response展示在界面上
        runOnUiThread(() -> textView.setText(response.toString()));
    } else {
        // 请求失败
        runOnUiThread(() -> textView.setText("请求失败"));
    }
} catch (Exception e) {
    e.printStackTrace();
}

以上代码通过URL对象构造了HTTP请求的URL地址,并通过openConnection方法获取了HttpURLConnection对象。然后设置了请求的方法为GET,并发送请求。如果请求成功,通过getResponseCode方法可以获取响应的状态码,如果状态码为200(HTTP_OK),则可通过getInputStream方法获取响应的输入流,并通过BufferedReader来读取输入流中的数据。

1.2 HttpClient

HttpClient是Android中的一个弃用的类,但在一些老的Android版本上可能仍然需要使用。以下是一个使用HttpClient发送GET请求的示例:

try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://www.example.com/user?id=1");

    HttpResponse response = httpClient.execute(httpGet);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder response = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }

        bufferedReader.close();
        inputStream.close();
        // 在UI线程中展示response
        runOnUiThread(() -> textView.setText(response.toString()));
    } else {
        // 请求失败
        runOnUiThread(() -> textView.setText("请求失败"));
    }
} catch (Exception e) {
    e.printStackTrace();
}

HttpClient与HttpURLConnection的实现原理类似,都是通过建立TCP连接发送HTTP请求,并获取响应结果。

二、HTTPS请求

HTTPS(Hypertext Transfer Protocol Secure)是在HTTP基础上增加了安全性的协议。在Android中,可以使用HttpsURLConnection或HttpClient来发送HTTPS请求。

2.1 HttpsURLConnection

HttpsURLConnection是HttpURLConnection的子类,用于发送HTTPS请求。以下是一个使用HttpsURLConnection发送GET请求的示例:

try {
    URL url = new URL("https://www.example.com/user?id=1");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("GET");

    int responseCode = connection.getResponseCode();
    if (responseCode == HttpsURLConnection.HTTP_OK) {
        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder response = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }

        bufferedReader.close();
        connection.disconnect();

        // 将response展示在界面上
        runOnUiThread(() -> textView.setText(response.toString()));
    } else {
        // 请求失败
        runOnUiThread(() -> textView.setText("请求失败"));
    }
} catch (Exception e) {
    e.printStackTrace();
}

与HttpURLConnection相比,HttpsURLConnection通过URL对象创建时使用的是https://而不是http://,并且需要将URLConnection对象转换为HttpsURLConnection对象。

2.2 HttpClient

HttpClient在发送HTTPS请求时需要使用SSL/TLS来确保数据的安全性。以下是一个使用HttpClient发送GET请求的示例:

try {
    HttpClient httpClient = new DefaultHttpClient();
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    SingleClientConnManager connectionManager = new SingleClientConnManager(httpClient.getParams(), schemeRegistry);
    HttpClient client = new DefaultHttpClient(connectionManager, httpClient.getParams());

    HttpGet httpGet = new HttpGet("https://www.example.com/user?id=1");

    HttpResponse response = httpClient.execute(httpGet);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder response = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            response.append(line);
        }

        bufferedReader.close();
        inputStream.close();

        // 在UI线程中展示response
        runOnUiThread(() -> textView.setText(response.toString()));
    } else {
        // 请求失败
        runOnUiThread(() -> textView.setText("请求失败"));
    }
} catch (Exception e) {
    e.printStackTrace();
}

HttpClient发送HTTPS请求时,需要使用SchemeRegistry和SSLSocketFactory来确保安全连接的建立。

三、总结

本文介绍了在Android中实现HTTP和HTTPS请求的方法。HTTP和HTTPS请求的基本原理是建立TCP连接发送请求,并获取服务器的响应结果。使用HttpURLConnection或HttpClient可以实现在Android应用程序中发送HTTP请求,而使用HttpsURLConnection或HttpClient可以实现发送HTTPS请求,从而提供更高的安全性。在实际开发中,根据具体的需求和环境来选择合适的网络请求方式。


全部评论: 0

    我有话说: