
Create a Dynamic Web Project in Eclipse. Let's say the name of the project is URLconnect.
In the left panel of Eclipse, at the name of your project (URLconnect in this example) > Java Resources > src, create a new package. For the sake of this tutorial, let's name the package com.main.
In the com.main package create a class called connect.
In connect.java, add the following markup to get the HTTP response code when from http://www.example.com.
package com.main;
import java.io.IOException;
import java.net.*;
public class connect {
public String myConnect() {
String responsecode = "";
try {
URL myurl = new URL("https://www.example.com/");
HttpURLConnection httpCon = (HttpURLConnection) myurl.openConnection();
int responseCode = httpCon.getResponseCode();
System.out.println("HTTP response code = " + responseCode);
responsecode = ("HTTP response code = " + responseCode);
} catch (IOException e) {
e.printStackTrace();
}
return responsecode;
}
}
In the left panel of Eclipse, right click on the name of your project (URLconnect in this example) and select New > JSP File. Select the WebContent folder, give the file a name such as index.jsp, and select Finish.
Add the following to line 1 of the JSP file. This is the combination of the package (com.main) and the class (URLconnect.java).
<%@page import="com.main.URLconnect"%>
Add the following inside the <body> tags.
- In this example, "connect" must be used because the name of the class in URLconnect.java is connect.
- In this example, "myConnect" must be used because the name of the method in URLconnect.java is myConnect.
<body>
<%
connect foo = new connect();
out.println(foo.myConnect());
%>
</body>
Select the green play button in Eclipse, and the HTTP response code from http://www.example.com should be returned.
Did you find this article helpful?
If so, consider buying me a coffee over at