Search code examples
javapostapache-httpclient-4.x

Creating a UrlEncodedFormEntity from a List of NameValuePairs throws a NullPointerException


I'm creating a unit test to try out the servlet I just created.

@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);
}

The following line generates a NullPointerException:

post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Is there something I'm missing?


Solution

  • Just solved it by adding the utf-8 format.

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

    Creating a UrlEncodedFormEntity without passing the format will use DEFAULT_CONTENT_CHARSET which is ISO-8859-1

    Which baffles me... what's causing it to throw NullPointerException?