我正在创建一个单元测试来尝试我刚刚创建的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));
有什么我想念的吗?
很抱歉这个愚蠢的问题,只需添加utf-8格式即可解决。
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
创建一个UrlEncodedFormEntity没有经过格式将使用DEFAULT_CONTENT_CHARSET这ISO-8859-1
UrlEncodedFormEntity
DEFAULT_CONTENT_CHARSET
ISO-8859-1
哪个让我感到困惑…是什么导致它抛出NullPointerException?
NullPointerException