Networking
Networking is an essential part of many Android applications, as it enables communication with servers and web services. The Android SDK provides several classes for networking such as HttpURLConnection and OkHttp.
Here's an example of how to make a network request using HttpURLConnection:
scss
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseData = response.toString();
}
conn.disconnect();
No comments:
Post a Comment