android使用httpurlconnection
时间: 2023-04-30 18:05:39 浏览: 134
为了使用HttpURLConnection来发送和接收HTTP请求和响应,您需要按照以下步骤操作:
1. 创建HttpURLConnection对象,并将其连接到URL对象。例如:
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
2. 设置请求方法和连接属性,如连接超时和读取超时。例如:
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
3. 添加请求头(可选)。例如:
conn.setRequestProperty("User-Agent", "Android");
conn.setRequestProperty("Content-Type", "application/json");
4. 如果POST请求,添加请求体。例如:
String requestBody = "{\"username\":\"user123\",\"password\":\"pass123\"}";
OutputStream outputStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
5. 发送请求,获取响应码和响应数据。例如:
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder responseData = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseData.append(line);
}
reader.close();
inputStream.close();
String responseString = responseData.toString();
}
以上是使用HttpURLConnection发送和接收HTTP请求和响应的基本步骤。具体实现需根据具体的业务需求和网络情况进行调整和优化。
阅读全文