写一个Java请求接口
时间: 2023-01-28 21:07:37 浏览: 88
下面是如何用Java发送简单的HTTP请求的示例代码:
```
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Example {
public static void main(String[] args) throws IOException {
// 创建URL对象
URL url = new URL("http://www.example.com/");
// 打开连接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 设置请求方法
con.setRequestMethod("GET");
// 获取响应状态码
int status = con.getResponseCode();
// 判断响应状态码是否是200
if (status == 200) {
// 读取响应内容
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println(content.toString());
} else {
// 打印响应状态码
System.out.println("HTTP GET Request Failed with Error code : " + status);
}
}
}
```
这个示例代码会发送一个GET请求到"http://www.example.com/",并输出响应内容。