java发起get请求代码
时间: 2023-09-07 16:17:42 浏览: 76
以下是Java发起GET请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) throws Exception {
String url = "https://www.example.com/api/getData";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//设置请求方法为GET
con.setRequestMethod("GET");
//添加请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("发送GET请求到URL:" + url);
System.out.println("响应代码:" + 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());
}
}
```
在这个示例中,我们使用`java.net.HttpURLConnection`类来发起GET请求。我们首先创建一个`URL`对象,然后使用`openConnection()`方法来获取`HttpURLConnection`对象。我们可以设置请求方法为GET,添加请求头,并使用`getResponseCode()`方法获取响应代码。最后,我们可以读取响应内容并将其打印出来。
阅读全文