写一段Java代码,要求使用Java标准库里的httpmethod方法,通信要求get形式,要用getResponseBodyAsString()返回数据并打印出来,请给出例子
时间: 2023-06-15 12:05:31 浏览: 101
下面是一个使用Java标准库中的httpmethod方法,以get形式通信,并使用getResponseBodyAsString()返回数据并打印出来的示例代码:
```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
String urlString = "https://www.example.com";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
System.out.println("Error: " + responseCode);
return;
}
Scanner scanner = new Scanner(conn.getInputStream());
scanner.useDelimiter("\\Z");
String responseBody = scanner.next();
scanner.close();
System.out.println(responseBody);
}
}
```
在这个示例中,我们使用了Java标准库中的HttpURLConnection类来建立连接。然后,我们设置请求方法为GET,并连接到指定的URL。
接下来,我们检查响应代码是否为200,如果不是,我们将打印错误消息并退出程序。如果响应代码是200,我们使用Scanner类读取响应主体,并将其作为字符串打印到控制台上。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)