在Java中处理HTTP错误码,通常是通过使用HTTP客户端库来发送HTTP请求并接收响应。当服务器返回一个错误码(如404 Not Found或500 Internal Server Error)时,客户端可以检查响应的状态码并根据需要采取相应的行动。
以下是使用Java内置的HttpURLConnection类和第三方库Apache HttpClient来处理HTTP错误码的示例。
HttpURLConnectionimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpErrorHandling {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
// Success
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
System.out.println("Response: " + content.toString());
} else {
// Error handling
System.out.println("HTTP Error Code: " + responseCode);
BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
String errorLine;
StringBuilder errorContent = new StringBuilder();
while ((errorLine = errorReader.readLine()) != null) {
errorContent.append(errorLine);
}
errorReader.close();
connection.disconnect();
System.out.println("Error Response: " + errorContent.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
首先,你需要将Apache HttpClient库添加到项目的依赖中。如果你使用Maven,可以在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
然后,你可以使用以下代码来处理HTTP错误码:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpErrorHandling {
public static void main(String[] args) {
HttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("http://example.com");
try {
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
// Success
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Response: " + responseBody);
} else {
// Error handling
System.out.println("HTTP Error Code: " + statusCode);
String errorResponseBody = EntityUtils.toString(response.getEntity());
System.out.println("Error Response: " + errorResponseBody);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这两个示例中,我们都检查了HTTP响应的状态码。如果状态码表示成功(2xx),我们读取并打印响应体。如果状态码表示错误(4xx或5xx),我们读取并打印错误响应体。这样,你就可以根据服务器返回的错误码来采取适当的措施。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。