java 发送 http请求 代码
时间: 2023-10-11 09:07:04 浏览: 82
java发送http请求
5星 · 资源好评率100%
好的,以下是 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());
}
}
```
希望能帮到您。如果您有任何其他问题,欢迎继续提问。
阅读全文