Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a UrlEncodedFormEntity from a List of NameValuePairs throws a NullPointerException

Tags:

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?

like image 723
Kevin D. Avatar asked Jun 08 '12 01:06

Kevin D.


2 Answers

Sorry for the stupid question, 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?

like image 165
Kevin D. Avatar answered Sep 28 '22 13:09

Kevin D.


Not a stupid question at all. I think the confusion is that in httpclient 4.1, no encoding format was required- This worked:

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

When I changed the dependency to httpclient 4.2 in order to access URIBuilder, I got:

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)... 

With 4.2, it seems the constructor requires the encoding, as you noted. Confusingly, the doc specifies that the old constructor is still available, but it doesn't seem to work anymore.

public UrlEncodedFormEntity(List parameters) doc

like image 41
Max P Magee Avatar answered Sep 28 '22 12:09

Max P Magee