Use the example code of GET request with the Request framework in the Java class library
The example code that uses the Request framework in the Java Library to send GET requests is as follows:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("http://example.com");
// Create HTTPURLCONNECTION object
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the request method to get
conn.setRequestMethod("GET");
// Get the response code
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// Read the response content
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
// Printing response content
System.out.println(response.toString());
in.close();
} else {
System.out.println ("Get request failed, response code:" + Responsecode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above code is a simple example that demonstrates how to use the Request framework in the Java class library to send a GET request.In an example, we first created a URL object, and then used the URL object to open a httpurlconnection connection.Next, we set the request method to get and get the response code.
If the response code is http_ok (that is, 200), it means that the request is successful. We can obtain the input stream by the conn.getInputStream () method and read the response content with BufferedReader.Finally, we print out the response content.
If the response code is not 200, it means that the request fails, and we can make an error treatment according to actual needs.
This sample code can help you quickly understand how to use the Request framework in the Java class library to send a GET request and get the results of the response.You can further expand and modify according to your needs.