本文介绍了从NameValuePairs列表创建UrlEncodedFormEntity会抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个单元测试来试用我刚刚创建的servlet。
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);
}
以下行生成NullPointerException:
The following line generates a NullPointerException:
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
我有什么遗漏吗?
推荐答案
很抱歉这个愚蠢的问题,只需添加utf-8格式即可解决。
Sorry for the stupid question, just solved it by adding the utf-8 format.
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
创建如果没有传递格式将使用 DEFAULT_CONTENT_CHARSET
这是 ISO-8859-1
其中让我感到困惑......是什么导致它抛出 NullPointerException
?
Which baffles me... what's causing it to throw NullPointerException
?
这篇关于从NameValuePairs列表创建UrlEncodedFormEntity会抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!