Java - sending HTTP parameters via POST method easily
To send HTTP parameters via the POST method in Java, you can use the java.net.URL
and java.net.HttpURLConnection
classes. Here is an example of how you can do this:
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
String urlParameters = "param1=value1¶m2=value2";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = "https://example.com";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
This code sends a POST request to the specified URL with the specified parameters. The response code and the response body are printed to the console.
Note that this example uses the application/x-www-form-urlencoded
content type, which is the most common content type for POST requests. This content type specifies that the request body contains URL-encoded parameters.
You can also use other content types, such as application/json
, if the server expects a different format for the request body.