In this article, we will show you a few examples to make HTTP GET/POST requests via the following APIs
- Apache HttpClient 4.5.10
- OkHttp 4.2.2
- Java 11 HttpClient
- Java 1.1 HttpURLConnection (Not recommend)
1. Apache HttpClient
In the old days, this Apache HttpClient is the de facto standard to send an HTTP GET/POST request in Java.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
package com.mkyong.http;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HttpClientExample {
// one instance, reuse
private final CloseableHttpClient httpClient = HttpClients.createDefault();
public static void main(String[] args) throws Exception {
HttpClientExample obj = new HttpClientExample();
try {
System.out.println("Testing 1 - Send Http GET request");
obj.sendGet();
System.out.println("Testing 2 - Send Http POST request");
obj.sendPost();
} finally {
obj.close();
}
}
private void close() throws IOException {
httpClient.close();
}
private void sendGet() throws Exception {
HttpGet request = new HttpGet("https://www.google.com/search?q=mkyong");
// add request headers
request.addHeader("custom-key", "mkyong");
request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");
try (CloseableHttpResponse response = httpClient.execute(request)) {
// Get HttpResponse Status
System.out.println(response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
Header headers = entity.getContentType();
System.out.println(headers);
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
}
private void sendPost() throws Exception {
HttpPost post = new HttpPost("https://httpbin.org/post");
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", "abc"));
urlParameters.add(new BasicNameValuePair("password", "123"));
urlParameters.add(new BasicNameValuePair("custom", "secret"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
Read more Apache HttpClient examples
2. OkHttp
This OkHttp is very popular on Android, and widely use in many web projects, the rising star.
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.2</version>
</dependency>
package com.mkyong.http;
import okhttp3.*;
import java.io.IOException;
public class OkHttpExample {
// one instance, reuse
private final OkHttpClient httpClient = new OkHttpClient();
public static void main(String[] args) throws Exception {
OkHttpExample obj = new OkHttpExample();
System.out.println("Testing 1 - Send Http GET request");
obj.sendGet();
System.out.println("Testing 2 - Send Http POST request");
obj.sendPost();
}
private void sendGet() throws Exception {
Request request = new Request.Builder()
.url("https://www.google.com/search?q=mkyong")
.addHeader("custom-key", "mkyong") // add request headers
.addHeader("User-Agent", "OkHttp Bot")
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Get response body
System.out.println(response.body().string());
}
}
private void sendPost() throws Exception {
// form parameters
RequestBody formBody = new FormBody.Builder()
.add("username", "abc")
.add("password", "123")
.add("custom", "secret")
.build();
Request request = new Request.Builder()
.url("https://httpbin.org/post")
.addHeader("User-Agent", "OkHttp Bot")
.post(formBody)
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Get response body
System.out.println(response.body().string());
}
}
}
Read more OkHttp examples
3. Java 11 HttpClient
In Java 11, a new HttpClient is introduced in package java.net.http.*
The sendAsync() will return a CompletableFuture, it makes concurrent requests much easier and flexible, no more external libraries to send an HTTP request!
package com.mkyong.http;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class Java11HttpClientExample {
// one instance, reuse
private final HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
public static void main(String[] args) throws Exception {
Java11HttpClientExample obj = new Java11HttpClientExample();
System.out.println("Testing 1 - Send Http GET request");
obj.sendGet();
System.out.println("Testing 2 - Send Http POST request");
obj.sendPost();
}
private void sendGet() throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://httpbin.org/get"))
.setHeader("User-Agent", "Java 11 HttpClient Bot")
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
}
private void sendPost() throws Exception {
// form parameters
Map<Object, Object> data = new HashMap<>();
data.put("username", "abc");
data.put("password", "123");
data.put("custom", "secret");
data.put("ts", System.currentTimeMillis());
HttpRequest request = HttpRequest.newBuilder()
.POST(buildFormDataFromMap(data))
.uri(URI.create("https://httpbin.org/post"))
.setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header
.header("Content-Type", "application/x-www-form-urlencoded")
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
}
private static HttpRequest.BodyPublisher buildFormDataFromMap(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if (builder.length() > 0) {
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
System.out.println(builder.toString());
return HttpRequest.BodyPublishers.ofString(builder.toString());
}
}
Read more Java 11 HttpClient examples
4. HttpURLConnection
This HttpURLConnection class is available since Java 1.1, uses this if you dare 🙂 Generally, it’s NOT recommend to use this class, because the codebase is very old and outdated, it may not supports the new HTTP/2 standard, in fact, it’s really difficult to configure and use this class.
The below example is just for self reference, NOT recommend to use this class!
package com.mkyong.http;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) throws Exception {
HttpURLConnectionExample obj = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
obj.sendGet();
System.out.println("Testing 2 - Send Http POST request");
obj.sendPost();
}
private void sendGet() throws Exception {
String url = "https://www.google.com/search?q=mkyong";
HttpURLConnection httpClient =
(HttpURLConnection) new URL(url).openConnection();
// optional default is GET
httpClient.setRequestMethod("GET");
//add request header
httpClient.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = httpClient.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(httpClient.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
//print result
System.out.println(response.toString());
}
}
private void sendPost() throws Exception {
// url is missing?
//String url = "https://selfsolve.apple.com/wcResults.do";
String url = "https://httpbin.org/post";
HttpsURLConnection httpClient = (HttpsURLConnection) new URL(url).openConnection();
//add reuqest header
httpClient.setRequestMethod("POST");
httpClient.setRequestProperty("User-Agent", "Mozilla/5.0");
httpClient.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
httpClient.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(httpClient.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
int responseCode = httpClient.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(httpClient.getInputStream()))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
//print result
System.out.println(response.toString());
}
}
}
Thank you for another great example. Can I ask you which JAR file the package java.net.http.* is in.
thank you so mutch
I couldn’t keep count of how many times your site has helped me.
You have my thanks sir !
Welcome.
I was wondering if I would need to send post requests to fill in a login form? I am not sure how I would do this using HttpClient and HTML 2.
Thanks mkyong for this tutorial, very informative and helpful.
I tried with Java versions 11, 12, 13 in Intellij, but java.net.http.HttpClient is not detected. Automatically sun.net.http.HttpClient is getting imported.
Cant we send request to a URL using sun.net.http.HttpClinet ?
My requirement is to read the data placed in a CSV file using URL.
I found this article useful.
I copy paste the above program in my eclipse getting , Exception in thread “main” java.net.UnknownHostException: http://www.google.com error , please let me know how to resolve this error
In 1. Apache HttpClient
if (entity != null) { …
is always true
getting 404 response
Sending ‘GET’ request to URL : http://www.google.com/search?q=mkyong
Response Code : 404
Exception in thread “main” java.io.FileNotFoundException: http://www.google.com/search?q=mkyong
404!? Which example you are referring?
hi, my url has some authentication so how can I pass credentials to the url
Try the authentication example.
https://www.mkyong.com/java/apache-httpclient-examples/
Hi,
I am trying to display the output from a simple while loop to angular front-end. Could you please help me in this regard?
Mkyoung you are the best java developer who can really teach other simple ! thank you men
Thanks man. Helped a lot
Hi
Can you please explain more about “sn”, “cn”, “locale”, “caller”, “num” ??
where can i get information of different parameters.
Thank you in advance
This is form parameters, just for POST demo.
Thank you SO much!!
Thank you so much!
Simple and clear.
Good luck to you!
hi
i am getting java.net.ConnectException: Connection refused: connect exception
simple and clear, nice job…
how to run this aplication on terminal ubuntu?
Thanks your blog is awesome …
Maybe consider using a StringBuilder instead of the StringBuffer?
Thanks, article is updated.
Post parameters : org.apache.http.client.entity.UrlEncodedFormEntity@548ad73b
Response Code : 302
302 FoundFoundThe document has moved here.
For Java HttpURLConnection example you use no try/catch. A developer who uses no try/catch should be buried alive
Hi, i am getting this exception when i try to open connection
Info: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I can not understand why open this connection requires a certificate. This is related with the agent used (mozilla)?
If you are using https instead of http you will get this type of validation error
nice website
very helpfull Thanks !!
could you also tell how to sen request body for a port call
Do you means POST? Article is updated with more examples.
Dude, this was a god send.
how about 3. Using Java Socket?
Hi,
I have a java standalone server which listen the request and then I open a socket connection. My requirement is, how can I know weather java client is using http or https protocol in my server programe.
What means this line of code?
String urlParameters = “sn=C02G8416DRJM&cn=&locale=&caller=&num=12345”;
form parameters.
Hi ,
After implementation i got below security related bug.
The call to HttpHost() (in my class on line 113 )uses an unencrypted protocol instead of an encrypted protocol to communicate with the server.
code:
private HttpHost getHttpProxy(String proxyHost,int proxyPort) {
return new HttpHost(proxyHost, proxyPort);
}
so how can i encrypt it?
Thank for Sharing this post with us. Very Helpfull and usefull Information. Hope you keep it up in future also by providing informative post.This Post is very much handy.Best of Luck & Cheers.
Thank You
Thank You for giving us idea about how to send HTTP request GET/POST in Java.
Thank You Very Much For Sharing Your Knowledge with US.Now a Day No Body Do what you did.We are really blessed with this types of informatic Posting. Hope you continue this in Future.Keep us updated with this this types of blogs.Best of Luck & Cheers.
Thanks David
how to post a JSON data to server(tomcat7) using POSTmethod
replace the next lines
List urlParameters = new ArrayList();
urlParameters.add(new BasicNameValuePair(“sn”, “C02G8416DRJM”));
urlParameters.add(new BasicNameValuePair(“cn”, “”));
urlParameters.add(new BasicNameValuePair(“locale”, “”));
urlParameters.add(new BasicNameValuePair(“caller”, “”));
urlParameters.add(new BasicNameValuePair(“num”, “12345”));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
with
post.setEntity(new StringEntity(“{“sn”:”C02G8416DRJM”}”,ContentType.create(“application/json”)));
Try this
https://www.mkyong.com/java/apache-httpclient-examples/
very helpfull Thanks !!
I just copied the post method u’ve created and wanted to use it somewhere the same way as you did. It is just like your class but without the get() thing
when I run it on one site of mine i get:
java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection
at tests.web.POSTRequestTest.sendPost(POSTRequestTest.java:32)
at tests.web.POSTRequestTest.main(POSTRequestTest.java:18)
you have change the HttpsURLConnection to HttpURLConnection
Article is updated, if possible, do not use
HttpURLConnection, try Apache HttpClient or OkHttpThank you very very much <3
I dont understand the method for the http connection example could someone please explain it using an example . you know one with an actual url and parameters and api call
Hi,
Thank you for these useful examples!
When I used the Java Post example, I’ve encountered some issues when sending content than contains non English characters.
Investigating it showed that the cause is the usage of DataOutputStream.writeBytes(). From this class documentation: “Each character in the string is written out, in sequence, by discarding its high eight bits.”
The solution is to use:
Writer out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
out.write(urlParameters);
Hi all
The example with HttpURLConnection does not work, I have been looking for a solution but I have not found my error is this:
java.net.ConnectException: Connection refused: connect…
The server is active, port 8000 is active, it is in a local environment
this perfectly working. but when i use java Swing i can’t pass the parameters to urlParameters from jTextField.
CODE:
String urlParameters = “NAME=”+jTextField_name.getText()+”&address=”+jTextField_add.getText();
OUTPUT:
Post parameters :NAME=&address=
also i assign “jTextField_name.getText()” to variable but output was same.
so can you solved this problem
“unable to find valid certification path to requested target”
This error is not a problem with the code sample given above but it means that the server that you are attempting to connect to is secured with a certificate. You will need to add that severs certificate to your local keystore.
Really Awesome! Thank you so much Really helped!
yeah thanks mkyong can already
for those cannot just change this line
HttpClientExample http = new HttpClientExample();
HI mkyong why i have this error ?
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – cannot find symbol
symbol: class HttpURLConnectionExample
location: class lab1.Lab1
at lab1.Lab1.main(Lab1.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
learn how to write java programs first maybe
Can you describe not how to send but how to recieve POST or GET request? I would like to recieve POST for example, but without using servlets. I would rather use JQuery and send POST to .jar file. Can it be done?
publishing the article is ok. how come the same work for you and not for others.
Does mkyong ever respond to questions or posts..?
HttpUrlConnection is synchronous or asynchronous
You have forgotten to write version of Apache HttpClient. Your code is @deprecated for version 4.5.1.
provide the solution
i am getting connection time out error………and javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException
When I connect to Bing or Yahoo I dont need to provide User-Agent but when I connect to Yahoo, I do need to provide User-Agent, what is the reason?
This is just what I needed!!!! I already use this code in my code, and it works like a charm
thanks for the post
I noticed that the connections are never disconnected. Is there a reason for that?
If I have given the Url of a jsp page and set parameters using setEntity, how can i get those parameters in the jsp page? Please help.
HttpClient jar does not provide HttpResponse class.
i am using httpclient-4.4.1.jar
how can i get httpresponse?
how can i send the data to the server using the PUT Method over HttpsUrlConnection?
Which is the most efficient and powerful way, Built-in or Apache Library ??
Respected sir,
sir i am working in the BSNL in INDIA as a ADSL broadband engineer.
i configure lots of modem in a day using web based configuration of the adsl modem like..tplink , linksys cisco , netgear etc…..
sir i used only 4 variable parameter like PPPOE USERNAME…PPPOE PASSWORD….SSID…WIFIPASSWORD…..
Sir i want to build a desktop application using java which automatic configure my adsl modem .
is it possible to do such using get and post method like login to gmail ?
my e mail is –[email protected]
Thanks for nice tut. But i have a problem when using http request to get response from website which using javascript to loading data. Any one tell me how to get all data contents from website using JS to load data. I have used Jsoup but i can’t get data. Many thanks.
You are really awesome..!, thanks for making such a nice blog
Thank you very much! Your code always so simple, so understandable and so workable!
how to download images
I love you, Mkyong!!! Your codes are always easy to use and perfect!!! Thanks a lot! 🙂
Hi,
How can I send the GET request to specific URL but using a port number for the host?
Thanks,
Razvan
in the url of the host add :
example: http://example.com:80
hello , is this same as a server and client?
Thanks! This is the exact example I needed to see.
If my teacher see, that you make a main in the class where you create the object, then he goes crazy
I’m getting this exception: Exception in thread “main” java.net.UnknownHostException: http://www.google.com
Thank you…
Sir i need to test webservices using java…I have framework build using selenium…please suggest how should i proceed….I am new to java…i see lot of articles which help develop webservice…publish it..etc
my simple problem statement is that we have webservices which has end point url…request…wsdl…and we want to capture the response (which can be xml or jason) and want to read and validate it…please suggest best possible way
Sir,I am trying to do exactly the same thing. Automate the testing of websevices using Java that is. Can you advise me on how to proceed. I hope you have completed your project.
same here i also want check the web services please suggest me.
Is there anyway I can make a continuous post request, because I get an error “Too many open files”.
Thanks a lot for this basic example.
Hi,
I have tried the above example “Send an HTTP GET request to Google.com to get the search result”
but I am getting the exception : “Exception in thread “main” java.net.ConnectException: Connection timed out: connect” so what could be the reason ?? Is there any set up is required or what ??
Please let me know how can I use this for TestNG and please give me a example.
ThnXss a Lot
thank you 🙂
First, you are The Man! Every time I google, your answers come up at the top! Thanks for sharing your knowledge.
I have a question about UrlConnection.connect(). I noticed you didn’t invoke that method. Does requesting the response code trigger an automatic connection?
thank you, it helped me very much
I have to upload file along with other request params. How to achieve that ?
hi there,
it’s strange – on get request i’ll get the whole HTML Content.
But when i do a post request, there will be nothing although the response code is 302 (found), the redirect url is the correct one.
any ideas on this? thanks
hi
i want to connect a web service its adreses are
Web Servisi Adresi :
real url : https://medeczane.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri
Test url : http://saglikt.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri
Web Servisi WSDL Adresi :
real WSDL : https://medeczane.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri/wsdl/SaglikTesisiReceteIslemleri.wsdl
Test WSDL: http://saglikt.sgk.gov.tr/eczanews/services/SaglikTesisiReceteIslemleri/wsdl/SaglikTesisiReceteIslemleri.wsdl
username is 99999999990 and passwork is 99999999990. i must send it with http header to gss server. i must send this request in every SOAP request. can you help me please…
Hi, I have a problem runing the first example, this is the error:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:271)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:328)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:793)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:896)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
Can you help me please?
PD, Sorry, but I don’t write in english good…
Hector,
From the machine where you’re running the program; are you able to open “http://www.google.com/search?q=mkyong” in browser ?
Did you solve this error if you are then please let me know on @puspitaparida:disqus
Hi,
I am trying to write similar code to check a server status.
However, i wish to retry up to 5 times in case of failure to connect.
Is there an option for that ?
package home.always.learning.java;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
*
*/
public class DialServer {
private static final String url = “http://localhost”;
private static final String requestMethod = “GET”;
// HTTP GET request
public static void main(String[] args) {
checkServer();
}
private static void checkServer() {
try {
sendGet();
} catch (ConnectException e) {
System.out.println(“Connect Exception..Try Again Till Max Attempts…”);
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
private static void sendGet() throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod(requestMethod);
System.out.println(con.getInputStream());
int responseCode = con.getResponseCode();
System.out.println(“Response Code : ” + responseCode);
}
}
You could check for other status codes, and using _if-esle_ you could call for the function again(for example if status is not(200)). To set it to check 5 times you could use a _for_ loop. Here is the list of http status codes: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Alex,
Thanks for your response. I did put the code to run in a loop and succeeded. However, if the server i am pinging is offline; i get a connect exception. Hence, i have to initiate my code to check again from the catch block. Per standards, is that a good thing to do, i.e. initiate a possible processing logic from catch block ???
Else, i did get the code to work.
public static void checkServer() {
for (int i = 0; i <= maxAttempts; i++) {
try {
int responseCode = sendGet();
if(responseCode==200)
{
System.out.println("Break Loop and Return");
break;
}
} catch (ConnectException e) {
if(i==maxAttempts)
{
System.out.println("Max Attempts Have Reached for Server Response…ALERT Now");
}
else
{
System.out.println("Connect Exception..Try Again Till Max Attempts…");
try {
Thread.currentThread().sleep(retryPeriod);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} catch (Exception e) {
System.out.println("Generic Exception Connecting To Server…");
e.printStackTrace();
}
}
}
“is that a good thing to do, i.e. initiate a possible processing logic from catch block ???”
I haven’t studied your code thouroughly, but I think that catching exceptions and trying a gin is one of the whole points of try-catch blocks. To have exceptions and still keep the program run without terminating with an exception thrown from the main() method.
I have asked for a review on the same point but did not receive much inputs.
However, i have observed some business scenarios where a business action will be performed in case an exception occurred. Considering this, i wrote the code involving catch.
Another reason was that if the server was not online; Java was throwing a connect exception and not giving some “code” to check the status. Else, an if-else construct would have helped me.
I wrote a program to implement my use case for recursive call to check server status periodically.
Following is the link to my post :
http://allzhere.in/2013/09/13/java-ping-server-status/
Good.
but,
spring mvc.
RestTemplate example?
Excellent examples over GET and POST method.