image/svg+xml $ $ ing$ ing$ ces$ ces$ Res Res ea ea Res->ea ou ou Res->ou r r ea->r ch ch ea->ch r->ces$ r->ch ch->$ ch->ing$ T T T->ea ou->r

Un client HTTP à la main

La classe HttpURLConnection

Concernant la version Android :

Propriétés système réseau

Initialisation d'une propriété système :

Utilisation d'URI et d'URL

Des classes pour URI et URL existent.

Une méthode pour télécharger un fichier

public void downloadFile(String url, String destination) 
  throws IOException
{
  try (
    InputStream is = new URL(url).openStream();
    OutputStream out = new FileOutputStream(destination);
  )  { transfer(is, out); }
}

Configuration de HttpURLConnection

HttpURLConnection conn = 
	(HttpURLConnection)new URL(url).openConnection();
// We can add a new header field
conn.addRequestProperty("headerName", "headerValue");
// We may specify a conditional retrieval
conn.setIfModifiedSince(time);
// We don't want to send data to the server
conn.setDoOutput(false);
// Now we connect to the server 
// (it could raise an IOException)
conn.connect()
// We retrieve the status code
int code = conn.getResponseCode();
// We can fetch a map of the response headers
Map<String, List<String>> map = conn.getHeaderFields();
// Some methods are predefined to fetch the common headers
String mime = conn.getContentType();
// We can work on the stream returned by the server
InputStream stream = conn.getInputStream();

Gestion des cookies (sous Android)

Exemples de code pour poster du contenu (méthode POST)

POST en urlencoded

public static void postURLEncoder(HttpURLConnection conn, Map<String, ?> data)
	throws IOException
{
		// Encode data
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setChunkedStreamingMode(0); 
		// We don't already know the total size, does not work with HTTP/1.0
		conn.connect();
		Writer w = new BufferedWriter(
			new OutputStreamWriter(conn.getOutputStream(), "ASCII"));
		boolean first = true;
		for (Map.Entry<String, ?> entry: data.entrySet())
		{
			if (! first) w.write("&"); // Add a separator
			else first = false;
			w.write(URLEncoder.encode(entry.getKey(), "UTF-8"));
			w.write("=");
			w.write(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
		}
		w.close();
}

POST en form-data (supporte les fichiers)

public static void postFormData(HttpURLConnection conn, Map<String, Object> data) throws IOException
{
	conn.setDoOutput(true);
	conn.setRequestMethod("POST");
	String boundary = Long.toHexString(new Random().nextLong()); // Random string for boundary
	conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
	conn.setChunkedStreamingMode(0);
	OutputStream os = new BufferedOutputStream(conn.getOutputStream());
	for (Map.Entry<String, Object> entry: data.entrySet())
	{
		if (entry.getValue() == null) continue;
		String header = "--" + boundary + "\r\n" 
			+ "Content-Disposition: form-data; field=\"" + entry.getKey() + "\"\r\n"
			+ "Content-Type: " + ((entry.getValue() instanceof String)?
				"text/plain; charset=UTF-8":"application/octet-stream") + "\r\n\r\n";
		os.write(header.getBytes("ASCII"));
		if (entry.getValue() instanceof String)
			os.write(entry.getValue().toString().getBytes("UTF-8"));
		else if (entry.getValue() instanceof InputStream)
		{
			InputStream is = (InputStream)entry.getValue();
			byte[] buffer = new byte[BUFFER_LEN];
			for (int r = is.read(buffer); r >= 0; r = is.read(buffer))
				os.write(buffer, 0, r);
		} else
			throw new IOException(
				"Object of type " + entry.getValue().getClass() + " is not supported");
		os.write("\r\n".getBytes("ASCII"));
	}
	os.write(("--" + boundary + "--\r\n").getBytes("ASCII"));
	os.close();
}