我尝试研究HttpURLConnection
Java源代码,以了解它如何基于套接字编程实现Http连接,但我遇到了如下问题:
/**
* Returns the value for the <code>n</code><sup>th</sup> header field.
* Some implementations may treat the <code>0</code><sup>th</sup>
* header field as special, i.e. as the status line returned by the HTTP
* server.
* <p>
* This method can be used in conjunction with the
* {@link #getHeaderFieldKey getHeaderFieldKey} method to iterate through all
* the headers in the message.
*
* @param n an index, where n>=0.
* @return the value of the <code>n</code><sup>th</sup> header field,
* or <code>null</code> if the value does not exist.
* @see java.net.HttpURLConnection#getHeaderFieldKey(int)
*/
public String getHeaderField(int n) {
return null;
}
在getResponseCode()
方法中,有一段代码如下:
/*
* If we can't a status-line then re-throw any exception
* that getInputStream threw.
*/
String statusLine = getHeaderField(0);
if (statusLine == null) {
if (exc != null) {
if (exc instanceof RuntimeException)
throw (RuntimeException)exc;
else
throw (IOException)exc;
}
return -1;
}
/*
* Examine the status-line - should be formatted as per
* section 6.1 of RFC 2616 :-
*
* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase
*
* If status line can't be parsed return -1.
*/
if (statusLine.startsWith("HTTP/1.")) {
int codePos = statusLine.indexOf(' ');
if (codePos > 0) {
int phrasePos = statusLine.indexOf(' ', codePos+1);
if (phrasePos > 0 && phrasePos < statusLine.length()) {
responseMessage = statusLine.substring(phrasePos+1);
}
// deviation from RFC 2616 - don't reject status line
// if SP Reason-Phrase is not included.
if (phrasePos < 0)
phrasePos = statusLine.length();
try {
responseCode = Integer.parseInt
(statusLine.substring(codePos+1, phrasePos));
return responseCode;
} catch (NumberFormatException e) { }
}
}
return -1;
为什么getHeaderField(int n)
总是返回null?有什么分?我该如何解释这两种方法?
答案 0 :(得分:2)
虽然它没有说出来,但HttpURLConnection被视为抽象基类(实际上并不是抽象的)。当你调用URL#openConnection()
时,你实际上得到了一个特定于编译器的类的实例;对于Sun / Oracle编译器,它是sun.net.www.protocol.http.HttpURLConnection。你会发现getHeaderField
的实现更有意义。