Creating a UrlEncodedFormEntity from a List of NameValuePairs throws a NullPointerException

孤人 提交于 2019-12-03 05:43:11
Kevin D.

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?

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!