21

作成したばかりのサーブレットを試すための単体テストを作成しています。

@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));

足りないものはありますか?

4

2 に答える 2

33

ばかげた質問で申し訳ありませんが、utf-8 形式を追加することで解決しました。

post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

UrlEncodedFormEntityフォーマットを渡さずに を作成すると、 DEFAULT_CONTENT_CHARSETwhich が使用されますISO-8859-1

どれが私を困惑させます...何がそれをスローさせているのNullPointerExceptionですか?

于 2012-06-08T02:33:57.223 に答える
10

ばかげた質問ではありません。混乱は、httpclient 4.1では、エンコード形式が必要なかったことだと思います-これは機能しました:

HttpEntity entity = new UrlEncodedFormEntity(params);
method.setEntity(entity);

URIBuilderにアクセスするために依存関係をhttpclient4.2に変更すると、次のようになります。

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)...

4.2では、ご指摘のとおり、コンストラクターにはエンコードが必要なようです。紛らわしいことに、ドキュメントには古いコンストラクターがまだ使用可能であると指定されていますが、それはもう機能していないようです。

public UrlEncodedFormEntity(List parameters)doc

于 2012-06-26T16:29:03.173 に答える