Android: URLConnection的setRequestProperty函数,这个方法有什么作用?

Android: setRequestProperty function of URLConnection, what does this method do?

虽然我知道Whosebug已经提问了,但是我真的不明白这个方法是干什么的。调试时我不能 "step into" 它 (F7)。我按 Ctrl-B 查看方法的主体,但它只有以下代码:

public void setRequestProperty(String field, String newValue) {
        checkNotConnected();
        if (field == null) {
            throw new NullPointerException("field == null");
        }
    }

checkNotConnected:

private void checkNotConnected() {
        if (connected) {
            throw new IllegalStateException("Already connected");
        }
    }

我的意思是,将值赋给字段的代码在哪里?任何解释表示赞赏。

更新(2015/08/08): 我找到了查看其实现的方法。由于它是抽象的,必须使用Ctrl-Alt-B 而不是Ctrl-B 来查看。

我猜你访问的方式不对,或者有某种受保护的代码...

原函数是这样的:

/**
 * 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);
}

在哪里 requests.set(key, value) 做你要求的:)!

这是 setRequestProperty() 的后台源代码

设置一般要求属性。如果具有该键的 属性 已经存在,则用新值覆盖它的值。

注意:HTTP 要求所有可以合法地拥有具有相同键的多个实例的请求属性使用逗号分隔的列表语法,该语法允许将多个属性附加到单个 属性.

参数:

key 请求已知的关键字(例如,"accept")。 value 与之关联的值。

投掷: java.lang.IllegalStateException

如果已经连接 java.lang.NullPointerException

如果键为空 也可以看看: 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

我找到了查看其实现的方法。由于是抽象的,必须使用Ctrl-Alt-B而不是Ctrl-B才能查看。

setRequestProperty的后台源代码如下(在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);
            } 
        }
    }