Request-Response Flow
Connection Configuration Methods
- setAllowUserInteraction
- setDoInput
- setDoOutput
- setIfModifiedSince
- setUseCaches
- setDefaultAllowUserInteraction
- setDefaultUseCaches
Header Management
- setRequestProperty(key,value)
- addRequestProperty(key,value)
setRequestProperty replaces all existing values for a given key, effectively clearing and reassigning. addRequestProperty appends additional values to an existing key.
Sending URL Requests
After establishing a connection, send requests by transmitting parameters to the server using output streams:
- getOutputStream
Reading Responses
- getContent
- getHeaderField
- getInputStream
HttpURLConnection Architecture
Network connections require sockets, but HttpURLConnection operates at a higher abstraction level without direct socket configuration. This abstraction explains why HttpURLConnection is a abstract clas instantiated only through URL.openConnection().
While underlying network connections can be shared across multiple HttpURLConnection instances, each instance handles only one request. After request completion, close the InputStream or OutputStream to release network resources. For persistent connections, use disconnect() to close the underlying socket.
Configuration Examples
Serialized Objects
// Configure content type for serialized Java objects
// Without this setting, serialization may throw java.io.EOFException
httpConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
// URLConnection establishes connection
// getOutputStream implicitly calls connect()
OutputStream output = httpConnection.getOutputStream();
// Send serialized data
ObjectOutputStream objStream = new ObjectOutputStream(output);
objStream.writeObject(new String("Test payload"));
String Data
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
Implementation Example
BufferedReader inputReader = null;
OutputStreamWriter outputWriter = null;
HttpURLConnection httpConn = null;
String responseData = "";
try {
URL targetUrl = new URL(apiEndpoint);
httpConn = (HttpURLConnection) targetUrl.openConnection();
// Configure input/output streams
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Timeout settings
httpConn.setConnectTimeout(10000);
httpConn.setReadTimeout(10000);
// Disable caching for POST
httpConn.setUseCaches(false);
httpConn.setInstanceFollowRedirects(true);
// Request configuration
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestProperty("access_key", apiKey);
// Send JSON payload
outputWriter = new OutputStreamWriter(httpConn.getOutputStream(), "UTF-8");
outputWriter.write(jsonPayload);
outputWriter.flush();
// Process response
inputReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String currentLine;
while ((currentLine = inputReader.readLine()) != null) {
responseData += currentLine;
}
// Release connection
httpConn.disconnect();
JSONObject result = JSON.parseObject(responseData);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (outputWriter != null) outputWriter.close();
if (inputReader != null) inputReader.close();
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}