Java simple code: java.net.SocketException: Unexpected end of file from server

“Unexpected end of file” implies that the remote server accepted and closed the connection without sending a response. It’s possible that the remote system is too busy to handle the request, or that there’s a network bug that randomly drops connections. It’s also possible there is a bug in the server: something in the request … Read more

Digest authentication in Android using HttpURLConnection

The answer is, that HttpUrlConnection does not support digest. You therefore have to implement RFC2617 by yourself. You can use the following code as a baseline implementation: HTTP Digest Auth for Android. The steps involve (see RFC2617 for reference): If you get a 401 response, iterate over all WWW-Authenticate headers and parse them: Check if … Read more

Two way sync for cookies between HttpURLConnection (java.net.CookieManager) and WebView (android.webkit.CookieManager)

I’ve implemented my own idea. It’s actually pretty cool. I’ve created my own implementation of java.net.CookieManager which forwards all requests to the WebViews’ webkit android.webkit.CookieManager. This means no sync is required and HttpURLConnection uses the same cookie storage as the WebViews. Class WebkitCookieManagerProxy: import java.io.IOException; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.CookieStore; import java.net.URI; import java.util.Arrays; … Read more

is it possible to proccess JSON responses with the JDK or HttpComponents only?

Unfortunately, native JSON support was delayed past Java 9. But for the sake of sportmanship here is plain Java 8 hacky solution using Nashorn JavaScript engine without any external dependency: String json = “{\”foo\”:1, \”bar\”:\”baz\”}”; ScriptEngine engine = new ScriptEngineManager().getEngineByName(“nashorn”); Object o = engine.eval(String.format(“JSON.parse(‘%s’)”, json)); Map<String, String> map = (Map<String, String>) o; System.out.println(Arrays.toString(map.entrySet().toArray())); // [foo=1, … Read more

How do I persist cookies when using HTTPUrlConnection?

Its’ taken me a few hours but I managed to build a custom cookie storage myself. You have to attach this by doing this: public class application extends Application { @Override public void onCreate() { super.onCreate(); CookieManager cmrCookieMan = new CookieManager(new MyCookieStore(this.objContext), CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cmrCookieMan); } } Here’s the actual storage: /* * This is a … Read more

HttpUrlConnection.openConnection fails second time

The connection pool used by HttpURLConnection when it is keeping connections alive is broken such that it tries to use connections that have been closed by the server. By default Android sets KeepAlive on all connections. System.setProperty(“http.keepAlive”, “false”); is a workaround that disables KeepAlive for all connections so then you avoid the bug in the … Read more