Java HttpURLConnection Parameter Setup
In Java, you can use the HttpURLConnection class to establish an HTTP connection and send a request. You can customize your request by setting parameters such as the request method, request headers, request body, etc.
Here is an example of setting parameters.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("https://www.example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
// 设置请求体(如果需要)
String requestBody = "{\"key\": \"value\"}";
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
// 获取响应结果
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the example above, we first create a URL object and then use that URL object to open an HttpURLConnection connection. Next, we set the request method to “GET” and set the request header “Content-Type” to “application/json”. If needed, we can set the request body and then write it to the connection’s output stream.
Next, we can get the response code by calling the getResponseCode() method and obtain the response body by reading the connection’s input stream. Finally, we output the response code and response body, and close the connection.
Please note that this example is for demonstration purposes only, you may need to handle errors and exceptions in actual situations.