Question
How can I send an HTTP POST request to a server in Java?
URL url = new URL("http://www.example.com/page.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
byte[] input = "id=10".getBytes("utf-8");
os.write(input, 0, input.length);
os.close();
Answer
Sending an HTTP POST request in Java can be accomplished using the HttpURLConnection class. This allows you to connect to a web server and send data, such as parameters, to be processed by a server-side script like PHP.
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
// Define the URL
URL url = new URL("http://www.example.com/page.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set up connection properties
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// Prepare data to send
String urlParameters = "id=10";
// Send POST request
try (OutputStream os = connection.getOutputStream()) {
byte[] input = urlParameters.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Get response code
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
}
}
Causes
- Not setting the request method properly to POST.
- Forgetting to enable output on the connection with setDoOutput(true).
- Failing to handle encoding and converting the parameters appropriately.
Solutions
- Use HttpURLConnection for handling HTTP requests.
- Set the request method to POST using setRequestMethod("POST").
- Prepare the output stream correctly and write the parameters using the OutputStream.
Common Mistakes
Mistake: Not handling exceptions properly during URL connection.
Solution: Surround your connection code with try-catch blocks to handle IOException.
Mistake: Sending data without a proper content type.
Solution: Set the content type using connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded").
Helpers
- Java HTTP POST request
- send POST request Java
- Java HttpURLConnection
- Java web programming POST
- HTTP requests in Java