0

我有一个构建 HttpResponse 初始化程序的类。在应该返回的方法之一中,BasicNameValuePair我必须检查列表中是否有一个条目,其键或名称由字符串“名称”指定。

public List<BasicNameValuePair> getPostPairs() {
    if(mPostPairs == null || mPostPairs.size() < 1) {
        throw new NullPointerException(TAG + ": PostPairs is null or has no items in it!");
    }

    //there is no hasName() or hasKey() method :(
    if(!mPostPairs.hasName("action")) {
        throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");
    }

    return mPostPairs;
}

这该怎么做?如果使用 BasicNameValuePair 不可能,那还有什么替代方法?子类化和添加方法?

我需要将它用于 HttpPost,它的 setEntity 只接受这种类型:

public UrlEncodedFormEntity (List<? extends NameValuePair> parameters)
4

1 回答 1

2

似乎mPostPairs是一个List<BasicNameValuePair>,并且一个列表不知道存储了什么样的对象,您可以对其进行迭代并检查

boolean finded = false;
for (BasicNameValuePair pair : mPostPairs) {
    if (pair.getName().equals("action")) {
        finded = true;
        break;
    }
}
if (finded)
    return mPostPairs;
else
    throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");

或更短:

for (BasicNameValuePair pair : mPostPairs) 
    if (pair.getName().equals("action")) 
        return mPostPairs;
throw new IllegalArgumentException(TAG + ": There is no 'action' defined in the collections");
于 2014-08-13T00:16:08.853 回答