How can I get the description of ResponseCode of HttpURLConnection?
-
04-06-2021 - |
题
After calling the following code, getResponseCode()
returns the response code returned by the remote HTTP server. This code has a short description. How can I get its description programmatically in Android?
URL myurl = new URL(url);
URLConnection connection = myurl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
UPDATE
httpConnection.getResponseMessage()
sometimes returns "not found" whereas responseCode is valid
解决方案
try getResponseMessage()
, it will a string message you may interesting.
其他提示
Try
httpConnection.getResponseMessage()
The docs say:
Gets the HTTP response message, if any, returned along with the response code from a server. >From responses like: HTTP/1.0 200 OK HTTP/1.0 404 Not Found Extracts the Strings "OK" and "Not Found" respectively. Returns null if none could be >discerned from the responses (the result was not valid HTTP).
Maybe there isn't a message from your server? You can also write your own method which will return descriptions for codes. e.g
public static String getMessage(int code) {
switch(code) {
case 200: return "OK";
}
}
you're more than welcome to check the HTTP/1.1 RFC that holds exactly what you're looking for.