I'm working on a project where I'm creating a class to run http client requests (my class acts as a client). It takes in a url and a request method (GET, POST, PUT, etc) and I want to be able to parse the URL and open a HttpsURLConnection or HttpURLConnection based on whether it is https or http (assume the given urls will always be correct).
If I do the following:
URLConnection conn = url.openConnection();
Then that will automatically create a URLConnection that can accept both http and https, but if I do this then I can't find any way to set a request method (GET, POST, etc), since only the HttpsURLConnection or HttpURLConnection classes have the setRequestMethod method.
If I do something like the following:
if(is_https)
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
else
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Then the connections are created, but I can't access them outside of the if blocks.
Is it possible to do this, or should I just give up and use the apache httpclient classes?
connect method is called. When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com : try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL.
To close the connection, invoke the close() method on either the InputStream or OutputStream object. Doing that may free the network resources associated with the URLConnection instance.
Java.net.HttpURLConnection Class in Java Last Updated : 16 Oct, 2019 HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP specific features.
The class HttpUrlConnection can send requests, but first, we have to obtain an instance of it from an URL object: A connection offers many methods to configure it, like setRequestMethod and setRequestProperty.
You will be able to write code for uploading and downloading files, web pages; sending and retrieving HTTP requests and responses; and the like. URLConnection is the superclass of all classes that represent a connection between a Java application and a URL.
However, the implementations can be replaced on a per-class (static) or per-instance basis. All new HttpsURLConnection s instances will be assigned the "default" static values at instance creation, but they can be overriden by calling the appropriate per-instance set method (s) before connect ing.
HttpsURLConnection extends HttpUrlConnection, so you do not need the HttpsUrlConnection, you can just do
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With