Android Studio 使用HTTPURLConnection发送请求
时间: 2023-08-07 13:11:55 浏览: 111
要使用HTTPURLConnection发送请求,可以按照以下步骤进行:
1. 在AndroidManifest.xml文件中添加网络权限:
```
<uses-permission android:name="android.permission.INTERNET" />
```
2. 在子线程中使用HTTPURLConnection发送请求,例如:
```
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建URL对象
URL url = new URL("http://www.example.com/api");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 设置连接超时和读取超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 发送请求
connection.connect();
// 获取响应码
int responseCode = connection.getResponseCode();
// 获取响应数据
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
inputStream.close();
String responseData = response.toString();
// 处理响应数据
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
```
这个例子中发送了一个GET请求,获取了http://www.example.com/api的响应数据。你可以根据需要设置请求方法、请求参数、请求头等。获取响应数据后,可以在UI线程中更新UI或者在子线程中处理响应数据。
阅读全文
相关推荐


















