十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
在Java中,我们可以使用HttpURLConnection或者HttpClient来获取HTTP状态码,这两种方式都可以实现对HTTP请求的响应进行检测和处理,下面分别介绍这两种方法。

HttpURLConnection是Java标准库中的一个类,它可以用来发送HTTP请求并接收响应,我们可以通过它的getResponseCode()方法来获取HTTP状态码。
以下是一个示例代码:
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println("HTTP状态码: " + responseCode);
connection.disconnect();
}
}
HttpClient是一个第三方库,它提供了一种更灵活的方式来处理HTTP请求,我们可以通过它的execute方法来发送HTTP请求,并通过Future的方法来获取HTTP状态码。
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("HTTP状态码: " + statusCode);
EntityUtils.consume(response.getEntity());
response.close();
} finally {
httpClient.close();
}
}
}
在上述两个示例中,我们都是通过获取HTTP状态码然后打印出来,实际上,我们可以根据不同的状态码进行不同的处理,如果状态码是200,那么我们就可以认为请求成功;如果状态码是404,那么我们就可以认为请求的资源不存在;如果状态码是500,那么我们就可以认为服务器内部错误等等,具体的处理方式需要根据实际的业务需求来确定。
问题1:如何使用HttpURLConnection设置请求头?
在创建HttpURLConnection对象后,可以使用setRequestProperty方法来设置请求头,connection.setRequestProperty("User-Agent", "Mozilla/5.0");,需要注意的是,有些请求头是不能被设置的,具体可以参考HTTP协议的相关文档。
问题2:如何使用HttpClient发送POST请求?
在创建HttpPost对象后,可以使用setEntity方法来设置要发送的数据体,post.setEntity(new StringEntity("{\"key\":\"value\"}", ContentType.APPLICATION_JSON));,只需要调用execute方法就可以发送POST请求了。