问题
Although I know that StackOverflow has already setRequestProperty function of HttpURLConnection question, I really don't understand what this method does. I cannot "step into" it (F7) when debugging. I pressed Ctrl-B to view the method's body, but it only has the following code:
public void setRequestProperty(String field, String newValue) {
checkNotConnected();
if (field == null) {
throw new NullPointerException("field == null");
}
}
and checkNotConnected
:
private void checkNotConnected() {
if (connected) {
throw new IllegalStateException("Already connected");
}
}
I mean that where is the code that puts the value to the field? Any explanation is appreciated.
UPDATE (2015/08/08): I have found the way to view its implementation. Since it's abstract, must use Ctrl-Alt-B instead of Ctrl-B to view.
回答1:
I guess you are accessing the wrong way, or have some kind of protected code...
The original function is this:
/**
* Sets the general request property. If a property with the key already
* exists, overwrite its value with the new value.
* ...
*/
public void setRequestProperty(String key, String value) {
if (connected)
throw new IllegalStateException("Already connected");
if (key == null)
throw new NullPointerException ("key is null");
if (requests == null)
requests = new MessageHeader();
requests.set(key, value);
}
Where requests.set(key, value)
do what you're asking for :)!
回答2:
this is back source code of setRequestProperty()
Sets the general request property. If a property with the key already exists, overwrite its value with the new value.
NOTE: HTTP requires all request properties which can legally have multiple instances with the same key to use a comma-seperated list syntax which enables multiple properties to be appended into a single property.
Parameters:
key the keyword by which the request is known (e.g., "accept"). value the value associated with it.
Throws:
java.lang.IllegalStateException
if already connected
java.lang.NullPointerException
if key is null See also: getRequestProperty(java.lang.String)
public void setRequestProperty(String key, String value) {
if (connected)
throw new IllegalStateException("Already connected");
if (key == null)
throw new NullPointerException ("key is null");
if (requests == null)
requests = new MessageHeader();
requests.set(key, value);
}
Source Link
回答3:
I have found the way to view its implementation. Since it's abstract, must use Ctrl-Alt-B
instead of Ctrl-B
to view.
And the back source code of setRequestProperty
as the following (inside jre\lib\rt.jar):
public void setRequestProperty(String var1, String var2) {
if(this.connected) {
throw new IllegalStateException("Already connected");
} else if(var1 == null) {
throw new NullPointerException("key is null");
} else {
if(this.isExternalMessageHeaderAllowed(var1, var2)) {
this.requests.set(var1, var2);
}
}
}
来源:https://stackoverflow.com/questions/31872868/android-setrequestproperty-function-of-urlconnection-what-does-this-method-do