常州阿里云代理商提供的关于Android 4.0的网络请求的解释:
在Android 4.0中,可以使用HttpURLConnection或Apache HttpClient的实现来进行网络请求。而目前推荐使用HttpURLConnection,因为它更加简洁、高效,并且支持较新的协议(如HTTP/2)。
以下是HttpURLConnection进行网络请求的示例代码:
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 可添加请求头信息
// connection.setRequestProperty("header", "value");
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// 得到响应内容后的处理
对于POST请求,需要设置请求方法为POST,并且设置请求体内容:
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// 添加请求体内容并设置Content-Type
OutputStream outputStream = connection.getOutputStream();
outputStream.write("request body".getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// 得到响应内容后的处理
需要注意的是,在Android 4.0中,网络请求不能在主线程中进行,需要在子线程中运行。最简单的实现方式是使用AsyncTask。
在Android 4.0上发送网络请求可以使用以下方法:
1.使用HttpURLConnection
HttpURLConnection是Android自带的网络连接类,可以用于发送HTTP请求和接收响应。
URL url = new URL("http://www.example.com/api/sample");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
String result = response.toString();
2.使用HttpClient
HttpClient是一个第三方库,可以在Android 4.0上使用。
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.example.com/api/sample");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer result = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
entity.consumeContent();
String resultString = result.toString();
注意:Android 6.0及以上版本已经移除了HttpClient库,应该使用HttpURLConnection代替。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/159850.html