Android使用URLConnection提交请求的实现攻略
在Android应用程序中,我们有时需要通过网络连接与服务器进行通讯,数据的传输有很多方式,其中常用的就是HTTP协议,而提交HTTP请求的方式也很多,比如常见的有Apache HttpClient、OkHttp等等。本文主要介绍基于JDK提供的URLConnection提交HTTP请求的方案。
Java中的URLConnection
Java中的URLConnection是一个抽象类,用于表示打开到URL所引用的资源的通信链接。它允许我们通过向输出流写入数据或者通过从输入流读取数据来与URLConnection的实例进行交互,从而完成HTTP客户端发送请求和接收响应的过程。
创建URLConnection对象
在使用URLConnection的时候,我们首先需要创建一个URLConnection对象。URLConnection类是一个抽象类,我们获取URLConnection的实例对象一般通过URL对象的openConnection方法。下面是如何创建一个URLConnection对象的代码示例:
URL url = new URL("http://www.example.com/");
URLConnection urlConnection = url.openConnection();
设置请求参数
我们可以通过URLConnection对象的setDoInput、setDoOutput、setRequestMethod等方法来配置HTTP请求的相关参数。其中setDoInput和setDoOutput方法分别用于设置URLConnection实例是否连接到输入和输出。如果setDoInput方法被设置为true,则打开输入流以从连接获取数据,否则为false。如果setDoOutput被设置为true,则打开输出流以向连接写入数据,否则为false。setRequestMethod方法则用于设置HTTP请求的方法。
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
设置请求头
在HTTP请求中,请求头是一个字符串,包含了请求的参数信息。与请求参数类似,我们可以通过setRequestProperty方法来设置HTTP请求头,如下所示:
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0...");
向服务器发送请求
在HTTP请求中,我们可以发送GET、POST、PUT、DELETE等各种类型的请求。但是最常见的就是GET和POST请求。
//构建POST请求体
String requestBody = "{\"name\": \"John\", \"age\": \"26\"}";
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.write(requestBody.getBytes("utf-8"));
outputStream.flush();
outputStream.close();
//向服务器发送请求
urlConnection.connect();
接收服务器响应
接收服务器响应可以通过获取URLConnection的输入流并将其转换为需要的类型来实现。如果响应数据是JSON格式的字符串,可以通过JsonParser将其转换为JsonElement对象,然后通过JsonElement.getAsJsonObject()将其转换为JsonObject对象。
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
inputStream.close();
urlConnection.disconnect();
//解析响应数据
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(response.toString()).getAsJsonObject();
示例1:提交GET请求
下面是一个使用URLConnection提交GET请求的例子:
try {
URL url = new URL("http://www.example.com/api/user?id=123456");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0...");
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
StringBuffer response = new StringBuffer();
String readLine = null;
while ((readLine = bufferedReader.readLine()) != null) {
response.append(readLine);
}
bufferedReader.close();
String responseData = response.toString();
Log.d("TAG", "GET请求返回数据:" + responseData);
} else {
Log.e("TAG", "GET请求失败,错误代码:" + responseCode);
}
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
示例2:提交POST请求
下面是一个使用URLConnection提交POST请求的例子:
try {
URL url = new URL("http://www.example.com/api/user");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0...");
//构建POST请求体
String requestBody = "{\"name\": \"John\", \"age\": \"26\"}";
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.write(requestBody.getBytes("utf-8"));
outputStream.flush();
outputStream.close();
//获取服务器响应
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
StringBuffer response = new StringBuffer();
String readLine = null;
while ((readLine = bufferedReader.readLine()) != null) {
response.append(readLine);
}
bufferedReader.close();
String responseData = response.toString();
Log.d("TAG", "POST请求返回数据:" + responseData);
} else {
Log.e("TAG", "POST请求失败,错误代码:" + responseCode);
}
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
以上就是使用URLConnection提交请求的完整攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Android使用URLConnection提交请求的实现 - Python技术站