gpt4 book ai didi

java - 从 NameValuePairs 列表创建 UrlEncodedFormEntity 会引发 NullPointerException

转载 作者:IT老高 更新时间:2023-10-28 20:44:42 26 4
gpt4 key购买 nike

我正在创建一个单元测试来试用我刚刚创建的 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_CHARSETISO-8859-1

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

关于java - 从 NameValuePairs 列表创建 UrlEncodedFormEntity 会引发 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com