Search code examples
javahttpcorsjsoup

Java JSOUP how to send the Origin in the header


im trying to test my service using JSOUP, but i'm using CORS, and i need to send the origin only for test porpouses, but when i send this i'dont receive on the server side, always receive null.

Connection con = Jsoup.connect("http://localhost:8080/myservice");
 con.userAgent("Mozilla");
 /* the origin is replaced to null automatically*/
 con.header("Origin", origin);
 con.ignoreHttpErrors(true);
 con.followRedirects(true);
 con.ignoreContentType(true);
 con.post();

I would do something diferent of this?

SOLVED:

Use ApacheHTTP instead JSOUP, cause JSOUP remove the Origin header by default. :)


Solution

  • Behind the scenes, JSoup is using a java.net.HttpURLConnection to make the connection. HttpURLConnection has a set of restricted headers, including "Origin". These don't seem to be well documented, but can be clearly seen in the source.

    As you mention using HttpClient will side step the problem.

    Alternatively, to continue with a direct connection from JSoup, depending what else is happening in your environment, it may be an option to set the sun.net.http.allowRestrictedHeaders system property. This can be seen further down in the source linked above.

    This will bypass the header checking in HttpURLConnection, but annoyingly it is coded as a shared static value. This means the system property will need to be set before the first connection is made anywhere in the JVM - e.g. as a -D command line option.

    There more about this topic over here.

    Digressing slightly, the comment in the HttpURLConnection source, comparing the restricted headers there to XMLHttpRequest2 is interesting - as if this is expecting to be run in a browser. This restriction may date back to the days of Java applets? It's perhaps less helpful now for server side applications.