在安卓开发中,设置网络URL通常涉及以下几个步骤:
1. 确定URL:你需要确定你想要访问的网络资源的URL。
2. 使用HttpURLConnection或OkHttp库:在Android中,你可以使用`HttpURLConnection`类或者第三方库如`OkHttp`来发起网络请求。
使用HttpURLConnection
以下是如何使用`HttpURLConnection`来设置和发起网络请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkUtil {
public static String sendGetRequest(String targetURL) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(targetURL);
// 打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);