2012年2月15日水曜日

[Android]Postが無視されるときの対処方法

とあるページのcgiにpostしようとしたときのお話しです。

いつもどおりpostしていたのですが、なぜか結果が反映されなかったのです。
コードはこちら。

HttpPost method = new HttpPost(url);
DefaultHttpClient client = new DefaultHttpClient();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("comment", content));
method.setEntity(new UrlEncodedFormEntity(params, "Shift_JIS"));
     
HttpResponse response = client.execute( method );
int status = response.getStatusLine().getStatusCode();
if ( status == HttpStatus.SC_OK ) {
res = EntityUtils.toString( response.getEntity(), "Shift_JIS" );
}


なぜ??ということでヘッダーを確認してみました。

urlencoded
Host: ホスト名
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)

User-Agentが怪しい。

という訳でUser-Agentを偽装して実行。
method.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");

おっ、できた。


コード全文はこちら。

HttpPost method = new HttpPost(url);
method.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
DefaultHttpClient client = new DefaultHttpClient();
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("comment", content));
method.setEntity(new UrlEncodedFormEntity(params, "Shift_JIS"));


HttpResponse response = client.execute( method );
int status = response.getStatusLine().getStatusCode();
if ( status == HttpStatus.SC_OK ) {
res = EntityUtils.toString( response.getEntity(), "Shift_JIS" );
}

※文字コードは適宜変えて使用すること。
 今回はたまたまShift-JISだっただけ。


ヘッダーはphpで出力確認しました。
HeaderとGetのパラメータ、Postのパラメータを確認する。 コードはこちら。

<?php
echo "<br>Headers:<br>";
$headers = getallheaders();
while (list ($header, $value) = each ($headers)) {
echo "$header: $value\n";
}

echo "<br>Get Parameters:<br>";
foreach( $_GET as $key => $value ) {
  echo htmlspecialchars($key) . "=" . htmlspecialchars($value) . "<BR>";
}

echo "<br>Post Parameters:<br>";
foreach( $_POST as $key => $value ) {
  echo htmlspecialchars($key) . "=" . htmlspecialchars($value) . "<BR>";
}
?>
http://gettingsignals.sakura.ne.jp/test/check_header.php

2012年2月1日水曜日

楽天トラベル:スマートフォンコンテスト優秀賞受賞

楽天トラベルさんで開催されていたスマートフォンアプリコンテストの結果発表があり、
私の作成した「旅宿」アプリがな・ん・と優秀賞を受賞しました。


Android初めて、4ヶ月目に作った4番目の作品です。

選ばれて賞いただけるというのは嬉しいですね。

今後もアプリ制作頑張っていきます。