作成したサーブレットを試すための単体テストを作成しています。
@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
私を困惑させるのは... NullPointerException
をスローする原因は何ですか?
まったく馬鹿げた質問ではありません。混乱は、httpclient 4.1ではエンコーディング形式が必要なかったことです-これはうまくいきました:
HttpEntity entity = new UrlEncodedFormEntity(params);
method.setEntity(entity);
RIBuilder にアクセスするために依存関係をhttpclient 4.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