从NameValuePairs列表创建UrlEncodedFormEntity会抛出NullPointerException

时间:2012-06-08 01:58:01

标签: java post apache-httpclient-4.x

我正在创建一个单元测试来试用我刚刚创建的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));

我有什么遗失的吗?

2 个答案:

答案 0 :(得分:32)

很抱歉这个愚蠢的问题,只需添加utf-8格式即可解决。

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

在不传递格式的情况下创建UrlEncodedFormEntity将使用DEFAULT_CONTENT_CHARSET <{1}} ISO-8859-1

令我感到困惑的是......是什么导致它抛出NullPointerException

答案 1 :(得分:11)

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

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

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

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时,似乎构造函数需要编码,如您所述。令人困惑的是,doc指定旧构造函数仍然可用,但它似乎不再起作用。

public UrlEncodedFormEntity(列出参数)doc