java发送网络请求代码
时间: 2023-03-30 19:04:22 浏览: 71
以下是一个简单的 Java 发送网络请求的示例代码:
```
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com/");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
```
这段代码可以向指定的 URL 发送 GET 请求,并打印出响应内容。如果需要发送 POST 请求,可以使用 HttpURLConnection 类。
相关问题
java发送http请求代码
以下是使用 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 地址、请求方法和其他参数。
java 发送 http请求 代码
好的,以下是 Java 发送 HTTP 请求的代码示例:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/getData";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("GET");
// 添加请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 发送 GET 请求
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println(response.toString());
}
}
```
希望能帮到您。如果您有任何其他问题,欢迎继续提问。