import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class HttpClientExample {
public static void main(String[] args) {
try {
// URL to make the GET request
URL url = new URL("https://httpbin.org/user-agent");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Setting the request method to GET
conn.setRequestMethod("GET");
// Optional: Set a custom User-Agent
// conn.setRequestProperty("User-Agent", "MyJavaApp/1.0");
// Reading the response
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Parsing the JSON response
JSONObject jsonResponse = new JSONObject(response.toString());
// Extracting the user-agent value
String userAgent = jsonResponse.getString("user-agent");
// Printing the user-agent to the console
System.out.println("User-Agent: " + userAgent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
-
Import Statements:
java.io.*: For input and output streams.
java.net.*: For network connections.
org.json.*: For parsing JSON. You might need to include a JSON library like JSON-java in your project.
-
Main Steps:
- Create a URL object with the endpoint
https://httpbin.org/user-agent.
- Open an HTTP connection using
HttpURLConnection.
- Set the request method to
GET.
- Optionally set request headers, like a custom
User-Agent.
- Read the response from the input stream.
- Build the response string from the input stream.
- Parse the JSON response using
JSONObject.
- Extract the
user-agent value from the JSON object.
- Print the value to the console.
Notes:
-
JSON Library: Ensure you have a JSON parsing library added to your project. You can use the org.json library or any other popular JSON library like Gson or Jackson.
-
Handling Exceptions: The try-catch block captures and prints any exceptions that might occur during the HTTP request or JSON parsing.
-
Custom User-Agent:
Sample Output:
When you run the program, it might output something like:
User-Agent: Java/17.0.1
The exact output depends on your Java version and whether you've set a custom User-Agent.
Dependencies:
If you're not using an IDE that automatically manages dependencies, you can download the JSON library (org.json.JSONObject) and add it to your classpath. Alternatively, if you're using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
Alternative Using HttpClient (Java 11 and above):
If you're using Java 11 or newer, you can use the built-in HttpClient API:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.JSONObject;
public class HttpClientExample {
public static void main(String[] args) {
try {
// Create HttpClient instance
HttpClient client = HttpClient.newHttpClient();
// Create HttpRequest instance
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://httpbin.org/user-agent"))
// Optionally set a custom User-Agent
// .header("User-Agent", "MyJavaApp/1.0")
.GET()
.build();
// Send the request and get HttpResponse
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Parsing the JSON response
JSONObject jsonResponse = new JSONObject(response.body());
// Extracting the user-agent value
String userAgent = jsonResponse.getString("user-agent");
// Printing the user-agent to the console
System.out.println("User-Agent: " + userAgent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This version uses the java.net.http.HttpClient class introduced in Java 11, simplifying the HTTP request process.
Remember: Always handle network operations and JSON parsing with proper error checking and resource management in production code.