今天看sun的HttpMessages.java文件,虽然文件很小,但是对我的启发很大。
前面定义了大量的HTTP常量:
也可以趁机从这里查看HTTP返回值的意义^_^。然后定义了一个java.util.concurrent.ConcurrentHashMap的变量httpStatusCodeMappings,再往里面添加刚才定义的常量(这个操作放在了一个静态块里),如:
[b]最重要的就是这个方法了,先看代码[/b]:
这段代码的用途很简单,就是要返回状态码对应的Message,而这些这些消息都已经存放在httpStatusCodeMappings变量里了,为了提高访问常用的几个返回码的Message,它直接用了一个静态块,而不去lookup那个map了,这就是高手!
前面定义了大量的HTTP常量:
...
...
private static final String STATUS_305 = "Use Proxy";
private static final String STATUS_307 = "Temporary Redirect";
private static final String STATUS_400 = "Bad Request";
private static final String STATUS_401 = "Unauthorized";
private static final String STATUS_402 = "Payment Required";
private static final String STATUS_403 = "Forbidden";
private static final String STATUS_404 = "Not Found";
private static final String STATUS_405 = "Method Not Allowed";
private static final String STATUS_406 = "Not Acceptable";
private static final String STATUS_407 = "Proxy Authentication Required";
private static final String STATUS_408 = "Request Timeout";
...
...
也可以趁机从这里查看HTTP返回值的意义^_^。然后定义了一个java.util.concurrent.ConcurrentHashMap的变量httpStatusCodeMappings,再往里面添加刚才定义的常量(这个操作放在了一个静态块里),如:
static {
httpStatusCodeMappings.put("sc.100", STATUS_100);
httpStatusCodeMappings.put("sc.101", STATUS_101);
httpStatusCodeMappings.put("sc.200", STATUS_200);
httpStatusCodeMappings.put("sc.201", STATUS_201);
httpStatusCodeMappings.put("sc.202", STATUS_202);
httpStatusCodeMappings.put("sc.203", STATUS_203);
...
...
[b]最重要的就是这个方法了,先看代码[/b]:
public static String getMessage(int status) {
// Return the status message for the most frequently used status
// codes directly, without any lookup
switch (status) {
case 200: return STATUS_200;
case 302: return STATUS_302;
case 400: return STATUS_400;
case 404: return STATUS_404;
}
return httpStatusCodeMappings.get("sc."+ status);
}
这段代码的用途很简单,就是要返回状态码对应的Message,而这些这些消息都已经存放在httpStatusCodeMappings变量里了,为了提高访问常用的几个返回码的Message,它直接用了一个静态块,而不去lookup那个map了,这就是高手!