URLConnection or HTTPClient: Which offers better functionality and more efficiency?

I believe in this case it’s up to whichever API you find more natural. Generally, HTTPClient is more efficient inside a server side application (or maybe batch application), because it allows you to specify a multithreaded connection pool, with a max number of total connections, and a max per host connection count (which ensures concurrent … Read more

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead. Below is the code to do that, URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty (“Authorization”, encodedCredentials); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) … Read more

Can you explain the HttpURLConnection connection process?

String message = URLEncoder.encode(“my message”, “UTF-8”); try { // instantiate the URL object with the target URL of the resource to // request URL url = new URL(“http://www.example.com/comment”); // instantiate the HttpURLConnection with the URL object – A new // connection is opened every time by calling the openConnection // method of the protocol handler … Read more

Upload files from Java client to a HTTP server

You’d normally use java.net.URLConnection to fire HTTP requests. You’d also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388. Here’s a kickoff example: String url = “http://example.com/upload”; … Read more

Convenient way to parse incoming multipart/form-data parameters in a Servlet [duplicate]

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you’re already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use … Read more

How to use java.net.URLConnection to fire and handle HTTP requests

First a disclaimer beforehand: the posted code snippets are all basic examples. You’ll need to handle trivial IOExceptions and RuntimeExceptions like NullPointerException, ArrayIndexOutOfBoundsException and consorts yourself. In case you’re developing for Android instead of Java, note also that since introduction of API level 28, cleartext HTTP requests are disabled by default. You are encouraged to … Read more