从 NameValuePairs 列表中创建 UrlEncodedFormEntity 会引发 NullPointerException

2022-09-02 03:04:47

我正在创建一个单元测试来尝试我刚刚创建的servlet。

@Test
public void test() throws ParseException, IOException {

  HttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost("http://localhost:8080/WebService/MakeBaby");

  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

  nameValuePairs.add(new BasicNameValuePair("father_name", "Foo"));
  nameValuePairs.add(new BasicNameValuePair("mother_name", "Bar"));

  post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  HttpResponse response = null;

  try {
    response = client.execute(post);
  } catch (ClientProtocolException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }

  String stringifiedResponse = EntityUtils.toString(response.getEntity());

  System.out.println(stringifiedResponse);

  assertNotNull(stringifiedResponse);
}

以下行生成 NullPointerException:

post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

我错过了什么吗?


答案 1

只是通过添加utf-8格式解决了它。

post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

创建 UrlEncodedFormEntity 而不传递格式将使用的格式DEFAULT_CONTENT_CHARSETISO-8859-1

这让我感到困惑...是什么导致它抛出?NullPointerException


答案 2

根本不是一个愚蠢的问题。我认为令人困惑的是,在httpclient 4.1中,不需要编码格式 - 这有效:

HttpEntity entity = new UrlEncodedFormEntity(params);
method.setEntity(entity);

当我为了访问URIBuilder而将依赖项更改为httpclient 4.2时,我得到了:

java.lang.NullPointerException
at org.apache.http.entity.StringEntity.<init>(StringEntity.java:70)
at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:78)
at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:92)...

在 4.2 中,构造函数似乎需要编码,如您所注意到的。令人困惑的是,该文档指定旧构造函数仍然可用,但它似乎不再起作用。

public urlEncodedFormEntity(List parameters) doc