本文介绍了从 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"));

创建一个UrlEncodedFormEntity 不传递格式将使用 DEFAULT_CONTENT_CHARSETISO-8859-1

这让我感到困惑...是什么导致它抛出 NullPointerException?

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

这篇关于从 NameValuePairs 列表创建 UrlEncodedFormEntity 会抛出 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 00:49