Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HttpServer Error: Access restriction: The type 'HttpServer' is not API

Tags:

java

I was trying to do something with the java HttpServer class.

This is the minimal example from the documentation:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;

class MyHandler implements HttpHandler 
{
    public void handle(HttpExchange t) throws IOException 
    {
        InputStream is = t.getRequestBody();
        read(is); // .. read the request body
        String response = "This is the response";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}

public class Main 
{
    HttpServer server = HttpServer.create(new InetSocketAddress(8000));
    server.createContext("/applications/myapp", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
}

But i get this error message:

Description Resource Path Location Type Access restriction: The type 'HttpServer' is not API (restriction on required library '/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/rt.jar') Main.java /test/src/test line 7 Java Problem

What does this even mean? According to the Oracle documentation this should work. Or am i getting this wrong?

like image 734
user2393256 Avatar asked Dec 12 '16 10:12

user2393256


2 Answers

The error message wants to say that you are accessing code that is not part of the official API for that library. More specifically, com.sun.net.httpserver.HttpServer is a class which is not guaranteed to be included in all Java 8 runtime implementations. Therefore, code using that class may fail in some Java installations.

In order to still be able to use this class, look into the answers to this question: Access restriction on class due to restriction on required library rt.jar?.

like image 177
Markus Fischer Avatar answered Oct 02 '22 19:10

Markus Fischer


Don't think so that you should use Sun's internal packages but still you can try disabling the error :

Go to Project properties -> Java Compiler -> Errors/Warnings -> Deprecated and restricted API

Also this post may help you.

If still the problem remains you can go with Christian Hujer's answer who says Eclipse has a mechanism called access restrictions to prevent you from accidentally using classes which Eclipse thinks are not part of the public API.

like image 31
Rahul Avatar answered Oct 02 '22 18:10

Rahul