要将Android(Java)应用程序中的http更新为HttpURLConnection,可以按照以下步骤进行操作:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
private String sendHttpRequest(String urlString) {
StringBuilder response = new StringBuilder();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
String url = "https://example.com/api/data";
String result = sendHttpRequest(url);
System.out.println(result);
这样,你就可以使用HttpURLConnection来发送http请求并获取响应了。请注意,上述代码仅包含了发送GET请求的示例,如果需要发送其他类型的请求(如POST),则需要做相应的修改。