Sending HTTP Requests in Java
HTTP requests are fundamental to web development, allowing clients to communicate with servers. In Java, sending an HTTP request involves utilizing the java.net.HttpUrlConnection class.
The following code snippet demonstrates how to construct and send an HTTP POST request:
public static String executePost(String targetURL, String urlParameters) { HttpURLConnection connection = null; try { URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { response.append(line).append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
This code creates a connection to the specified URL, sets the request method to POST, and adds necessary headers. It then writes the request parameters to the output stream and sends the request. The server's response is retrieved from the input stream and returned as a string.
The above is the detailed content of How to Send HTTP POST Requests in Java Using HttpURLConnection?. For more information, please follow other related articles on the PHP Chinese website!