java发送http请求代码
时间: 2023-09-14 17:10:47 浏览: 46
以下是使用 Java 发送 HTTP 请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("http://www.example.com");
// 创建 HttpURLConnection 对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
conn.setRequestMethod("GET");
// 发送请求
int responseCode = conn.getResponseCode();
// 打印响应码
System.out.println("Response Code: " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println("Response Content: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码使用 `java.net.HttpURLConnection` 类来发送 HTTP 请求。首先,创建一个 `URL` 对象,指定要发送请求的 URL 地址。然后,使用 `openConnection()` 方法创建一个 `HttpURLConnection` 对象。接下来,可以设置请求方法(例如 GET、POST),然后调用 `getResponseCode()` 方法获取响应码,调用 `getInputStream()` 方法获取响应内容的输入流,并读取响应内容。
请根据实际需求修改代码中的 URL 地址、请求方法和其他参数。