The HttpURLConnection is an of import course of education inwards java.net packet which allows you lot to shipping an HTTP asking from Java program. By using this you lot tin shipping whatever variety of HTTP asking e.g. GET, POST, PUT, DELETE, HEAD etc. It likewise provides several methods to configure your HTTP requests e.g. it allows you lot to add together headers, add together asking parameters, attaching cookie, configuring timeout, treatment redirects too hence on. Influenza A virus subtype H5N1 expert cognition of this course of education is of import for Java developers working on both meat Java too Java spider web application.
Sending HTTP asking is quite mutual inwards today's connected footing too fifty-fifty though a lot of powerful, third-party libraries e.g. Apache HttpClient exists inwards Java world, knowing how to create it without using tertiary political party library e'er matters.
If you lot know this class, you lot tin easily write around unit of measurement tests for your REST API similar you lot tin verify reply code, headers, too JSON payload.
In this article, I am going to present you lot around of the basic illustration of HttpURLConnection which volition learn you lot how to shipping HTTP asking from Java programme too configure it according to your need.
Though, if you lot are non familiar amongst Socket programming inwards Java too then I likewise propose you lot depository fiscal establishment fit the Java: Socket Programming Simplified, a costless course of education on Udemy.
And If you lot desire to acquire Java from Scratch, I propose you lot depository fiscal establishment fit out The Complete Java MasterClass course, most comprehensive too up-to-date course, which is of late updated for Java eleven every bit well.
1) Send a unproblematic GET request
You tin shipping an HTTP asking past times only creating a URL object amongst the actual URL too and then creating an HttpURLConnection from that. Btw, the actual asking is non sent until you lot perform around functioning e.g. reading a reply code or reading information from InputStream.
Here is a unproblematic code to shipping the most unproblematic GET asking to access your Github profile inwards Java program:
public course of education Hello {
public static void main(String args[]) throws IOException {
URL url = novel URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader inwards = novel BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
In this code, nosotros are reading reply business past times business too closing it in i trial nosotros are done amongst reading the response. Remember, the HttpURLConnection object tin locomote used exclusively to shipping i quest too that's why you lot must closed it later using it.
2) Send a POST request
The HttpConnection course of education likewise allows you lot to shipping a POST request, too non only POST past times whatever HTTP method e.g. PUT, DELETE or PATCH. All you lot ask to create is telephone telephone the setRequestMethod("POST") from HttpURLConnection amongst appropriate method mention e.g. POST to shipping a POST request.
Here is the code:
URL url = novel URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
Remember, if you lot desire to shipping Request parameters inwards the body, too then POST asking is the most appropriate request. See Complete Java Masterclass learn to a greater extent than close sending an HTTP asking from Java.
3) Check the Response Code
Checking the reply code is really tardily spell using HttpURLConnection, you lot tin only telephone telephone the getResponseCode() method too it volition render the fault or reply code every bit int. It volition likewise shipping the asking to the server if it's non shipping already.
Here is the code to retrieve resposne code inwards Java:
int code = con.getResponseCode();
If you lot remember, code inwards the 200 attain is for success, 400s are for client-side fault too 500s are for server-side error.
4) Dealing amongst Headers
You tin add together headers into HTTP asking past times calling the setRequestProperty() method of HttpURLConnection every bit shown below:
con.setRequestProperty("Content-Type", "application/json");
In this case, nosotros are setting the "Content-Type" header to "application/json" to dot that the asking is inwards JSON format. Similarly, you lot tin likewise retrieve header values from HTTP reply using getRequestProperty() method, which accepts header mention too render value e.g.
String header = con.getRequestProperty("Content-Type");
You tin role this to perform content negotiation spell accessing REST APIs inwards Java.
5) Dealing amongst Request Parameters
You tin likewise add together Request or Query parameters to your HTTP asking spell using HttpURLConnection class, but it's piffling fleck tricky. You get-go ask to enable the Connection object to write something on it too for that you lot ask to telephone telephone the setDoOutput() method.
After that you lot tin acquire the OutputStream from HttpURLConnection too write interrogation parameters into it inwards the shape of param1=value¶m2=value2¶m3=value3.
Here is around code to add together interrogation paramters into an HTTP asking using Java:
URL url = novel URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream dos = novel DataOutputStream(con.getOutputStream());
dos.writeChars("param1=value1¶m2=value2");
dos.flush();
dos.close();
They could have got done meliorate amongst this but that's what you lot have got when you lot are using HttpURLConnection. The choice API provided past times HttpClient library has meliorate back upward for adding asking parameter to HTTP request. See Java In-Depth: Become a Complete Java Engineer! to acquire to a greater extent than close dealing asking parameters for HTTP asking inwards Java.
6) Dealing amongst Cookies
You tin role the HttpCookie too CookiManager classes from java.net packet to both shipping too have Cookie from Java program. You tin retrieve the value of header "Set-Cookie" to retrieve cookies from reply too parse them using HttpCookie course of education every bit shown below:
String cookie = con.getHeaderField("Set-Cookie");
List<HttpCookie> cookies = HttpCookie.parse(cookie);
Similarly, you lot tin role the CookieManager course of education to shop the cookies into CookiStore every bit good every bit retreive stored cookies to attach amongst outgoing request. Just laid the "Cookie" header amongst the values every bit Cookies retrieved from shop every bit shown below:
con.setRequestProperty("Cookie", String.join(cookieManager.getCookieStore().getCookies(), ";"));
Btw, you lot ask to disconnect too Open the HttpURLConnection in i trial to a greater extent than because you lot tin exclusively role it i time.
7) Configuring Timeouts
One of the of import thing to regard spell making HTTP asking inwards production is setting upward timeouts, apparently you lot cannot facial expression forever for an HTTP asking to complete.
Thankfully, HttpURLConnection allows you lot to configure timeouts spell connecting every bit good every bit reading information using setConnectTimeout() too setReadTimeOut() method every bit shown below:
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
The values specified are a fourth dimension inwards milliseconds i.e. it volition facial expression for 10 seconds spell connecting to the server every bit good every bit spell reading information from the server.
That's all close around of the basic examples of HttpURLConnection course of education inwards Java. As I said, it's i of the essential networking course of education for JDK too every Java developer should locomote aware of that. You mightiness non ask this inwards your project, peculiarly if you lot are using HttpClient library but you lot must know that this is what JDK provides too every other third-party library volition used it furnish syntactic saccharide over it.
P. S. - If you lot desire to acquire to a greater extent than close Socket Programming inwards Java, I propose you lot depository fiscal establishment fit the Java: Socket Programming Simplified, a costless course of education on Udemy.
Sending HTTP asking is quite mutual inwards today's connected footing too fifty-fifty though a lot of powerful, third-party libraries e.g. Apache HttpClient exists inwards Java world, knowing how to create it without using tertiary political party library e'er matters.
If you lot know this class, you lot tin easily write around unit of measurement tests for your REST API similar you lot tin verify reply code, headers, too JSON payload.
In this article, I am going to present you lot around of the basic illustration of HttpURLConnection which volition learn you lot how to shipping HTTP asking from Java programme too configure it according to your need.
Though, if you lot are non familiar amongst Socket programming inwards Java too then I likewise propose you lot depository fiscal establishment fit the Java: Socket Programming Simplified, a costless course of education on Udemy.
And If you lot desire to acquire Java from Scratch, I propose you lot depository fiscal establishment fit out The Complete Java MasterClass course, most comprehensive too up-to-date course, which is of late updated for Java eleven every bit well.
HttpURLConnection Examples inwards Java
Here are around of the fundamentals code examples of using HttpURLConnection course of education inwards Java1) Send a unproblematic GET request
You tin shipping an HTTP asking past times only creating a URL object amongst the actual URL too and then creating an HttpURLConnection from that. Btw, the actual asking is non sent until you lot perform around functioning e.g. reading a reply code or reading information from InputStream.
Here is a unproblematic code to shipping the most unproblematic GET asking to access your Github profile inwards Java program:
public course of education Hello {
public static void main(String args[]) throws IOException {
URL url = novel URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader inwards = novel BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
In this code, nosotros are reading reply business past times business too closing it in i trial nosotros are done amongst reading the response. Remember, the HttpURLConnection object tin locomote used exclusively to shipping i quest too that's why you lot must closed it later using it.
2) Send a POST request
The HttpConnection course of education likewise allows you lot to shipping a POST request, too non only POST past times whatever HTTP method e.g. PUT, DELETE or PATCH. All you lot ask to create is telephone telephone the setRequestMethod("POST") from HttpURLConnection amongst appropriate method mention e.g. POST to shipping a POST request.
Here is the code:
URL url = novel URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
Remember, if you lot desire to shipping Request parameters inwards the body, too then POST asking is the most appropriate request. See Complete Java Masterclass learn to a greater extent than close sending an HTTP asking from Java.
3) Check the Response Code
Checking the reply code is really tardily spell using HttpURLConnection, you lot tin only telephone telephone the getResponseCode() method too it volition render the fault or reply code every bit int. It volition likewise shipping the asking to the server if it's non shipping already.
Here is the code to retrieve resposne code inwards Java:
int code = con.getResponseCode();
If you lot remember, code inwards the 200 attain is for success, 400s are for client-side fault too 500s are for server-side error.
4) Dealing amongst Headers
You tin add together headers into HTTP asking past times calling the setRequestProperty() method of HttpURLConnection every bit shown below:
con.setRequestProperty("Content-Type", "application/json");
In this case, nosotros are setting the "Content-Type" header to "application/json" to dot that the asking is inwards JSON format. Similarly, you lot tin likewise retrieve header values from HTTP reply using getRequestProperty() method, which accepts header mention too render value e.g.
String header = con.getRequestProperty("Content-Type");
You tin role this to perform content negotiation spell accessing REST APIs inwards Java.
5) Dealing amongst Request Parameters
You tin likewise add together Request or Query parameters to your HTTP asking spell using HttpURLConnection class, but it's piffling fleck tricky. You get-go ask to enable the Connection object to write something on it too for that you lot ask to telephone telephone the setDoOutput() method.
After that you lot tin acquire the OutputStream from HttpURLConnection too write interrogation parameters into it inwards the shape of param1=value¶m2=value2¶m3=value3.
Here is around code to add together interrogation paramters into an HTTP asking using Java:
URL url = novel URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream dos = novel DataOutputStream(con.getOutputStream());
dos.writeChars("param1=value1¶m2=value2");
dos.flush();
dos.close();
They could have got done meliorate amongst this but that's what you lot have got when you lot are using HttpURLConnection. The choice API provided past times HttpClient library has meliorate back upward for adding asking parameter to HTTP request. See Java In-Depth: Become a Complete Java Engineer! to acquire to a greater extent than close dealing asking parameters for HTTP asking inwards Java.
6) Dealing amongst Cookies
You tin role the HttpCookie too CookiManager classes from java.net packet to both shipping too have Cookie from Java program. You tin retrieve the value of header "Set-Cookie" to retrieve cookies from reply too parse them using HttpCookie course of education every bit shown below:
String cookie = con.getHeaderField("Set-Cookie");
List<HttpCookie> cookies = HttpCookie.parse(cookie);
Similarly, you lot tin role the CookieManager course of education to shop the cookies into CookiStore every bit good every bit retreive stored cookies to attach amongst outgoing request. Just laid the "Cookie" header amongst the values every bit Cookies retrieved from shop every bit shown below:
con.setRequestProperty("Cookie", String.join(cookieManager.getCookieStore().getCookies(), ";"));
Btw, you lot ask to disconnect too Open the HttpURLConnection in i trial to a greater extent than because you lot tin exclusively role it i time.
7) Configuring Timeouts
One of the of import thing to regard spell making HTTP asking inwards production is setting upward timeouts, apparently you lot cannot facial expression forever for an HTTP asking to complete.
Thankfully, HttpURLConnection allows you lot to configure timeouts spell connecting every bit good every bit reading information using setConnectTimeout() too setReadTimeOut() method every bit shown below:
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
The values specified are a fourth dimension inwards milliseconds i.e. it volition facial expression for 10 seconds spell connecting to the server every bit good every bit spell reading information from the server.
That's all close around of the basic examples of HttpURLConnection course of education inwards Java. As I said, it's i of the essential networking course of education for JDK too every Java developer should locomote aware of that. You mightiness non ask this inwards your project, peculiarly if you lot are using HttpClient library but you lot must know that this is what JDK provides too every other third-party library volition used it furnish syntactic saccharide over it.
Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!
Thanks for reading this article hence far. If you lot similar this article too then delight portion amongst your friends too colleagues.
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!
Thanks for reading this article hence far. If you lot similar this article too then delight portion amongst your friends too colleagues.
P. S. - If you lot desire to acquire to a greater extent than close Socket Programming inwards Java, I propose you lot depository fiscal establishment fit the Java: Socket Programming Simplified, a costless course of education on Udemy.
No comments:
Post a Comment