user2393256
user2393256

Reputation: 1150

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

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?

Upvotes: 6

Views: 10191

Answers (3)

user3801999
user3801999

Reputation: 11

Remove the JRE System Library from the build path and add it back. Select "Add Library" and select the JRE System Library. The default one should work.

BuildPath >> Libraries

Upvotes: 1

StackUseR
StackUseR

Reputation: 958

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.

Upvotes: 5

Markus Fischer
Markus Fischer

Reputation: 1366

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?.

Upvotes: 5

Related Questions