Categories
java

com.sun.net.httpserver.httpexchange not found in eclipse

In this post we will learn about com.sun.net.httpserver.httpexchange not found in eclipse

While I am trying to add Http Server in Core java application I faced below exception

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

If you are not to able to add above dependencies in java code, please verify below points

  • You should use java version above 1.6
  • Make sure you have configured correct JDK in your build path

If above things are correct still you are facing the issue means you need to do below thing in eclipse

you need to add com/sun/net/httpserver/ package in the access rule

  • Open Eclipse
  • Navigate to java build path
  • Click on the access rule under JRE System Libray
  • Click on the edit button and add an access rule like below image
Reference

https://stackoverflow.com/questions/13155734/eclipse-cant-recognize-com-sun-net-httpserver-httpserver-package

Related Articles

add rest service in core java application

Categories
java

add rest service in core java application

In this post, we will learn about add rest service in core java application

We are in spring boot world, where exposing a http endpoint is much easier, but when it comes to a standalone java application we will get confused

Java has a feature to expose Http endpoint from a standalone application.
Using import com.sun.net.httpserver.HttpExchange;

In below example, we are exposing an Http endpoint on port number 8080 with endpoint /health

Example

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerExample {

	public static void main(String[] args) throws Exception {
		try {
			HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
			server.createContext("/health", new Handler());
			server.setExecutor(null);
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	static class Handler implements HttpHandler {
		@Override
		public void handle(HttpExchange t) throws IOException {
			String response = "Up & Running";
			t.sendResponseHeaders(200, response.length());
			OutputStream os = t.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
	}
}
Output

http://localhost:8080/health

Up & Running

If you are not found com.net.sun.http package in your eclipse follow this URL https://beginnersbug.com/com-sun-net-httpserver-httpexchange-not-found-in-eclipse

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/HttpServerExample.java