用java完成一个http请求
时间: 2024-06-01 17:02:40 浏览: 16
你可以使用Java的标准库中的HttpURLConnection类来完成一个HTTP请求。以下是一个简单的示例代码:
```java
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) {
try {
URL url = new URL("https://www.example.com/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
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());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们创建了一个URL对象,指向我们要请求的API。然后,我们使用HttpURLConnection打开连接,并设置请求方法为GET。接下来,我们使用BufferedReader读取响应,并将其存储在一个StringBuffer对象中。最后,我们打印出响应的内容。