ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 获取URL请求状态 本篇简单介绍如果使用原生API发送HTTP请求 题目: 请求链接 https://www.baidu.com/ ,查看返回URL的状态 把这一部分单独拿出来,是我觉得有必要更深一步的理解http状态码的作用 ### 原生API请求获取HTTP返回状态 ``` package com.llg.book.http; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpResponseTest { public static void main(String[] args) throws MalformedURLException { String link = "https://www.baidu.com/"; URL url = new URL(link); System.out.println(getHttpResponseCode(url)); } public static int getHttpResponseCode(URL url) { HttpURLConnection httpurlconnection = null; int responsecode = -1; try { URLConnection urlconnection = url.openConnection(); urlconnection.connect(); if (!(urlconnection instanceof HttpURLConnection)) { // urlconnection.disconnect(); return responsecode; } httpurlconnection = (HttpURLConnection) urlconnection; // httpurlconnection.setFollowRedirects(true); // 获取返回码,通过responsecode 就可以知道网页的状态,我们也是通过此字段用于判断请求的资源是否存在 responsecode= httpurlconnection.getResponseCode(); switch (responsecode) { // here valid codes! case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: break; default: httpurlconnection.disconnect(); } } catch (Exception ioexception) { if (httpurlconnection != null) { httpurlconnection.disconnect(); } return responsecode; } return responsecode; } } ``` 执行以上代码,返回结果 ```200 ```