java如何发送get请求
时间: 2023-03-29 14:04:08 浏览: 159
Java可以使用HttpURLConnection或者HttpClient发送GET请求。其中HttpURLConnection是Java自带的API,HttpClient需要导入第三方库。以下是使用HttpURLConnection发送GET请求的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetRequest {
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com/api/getData");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文