|
|||||
Apache HttpClientを利用したHTTPアクセスApache HttpClientと言えばJavaプログラマにはおなじみのHTTPクライアント(4.x)であるが、Androidの場合はjarを持ってこなくても最初からHttpClientが利用できる。これはWebサーバにアクセスするプログラムを簡単に書くことができるのにも拘らず、認証も可能である等柔軟性も持ち合わせている。 Google Mapsのジオコーディングリクエスト以下はGoogle Mapsのジオコーディングリクエストを送信し、結果をXMLで得る例である。ジオコーディングとは、住所(が分かるようなキーワードでも可)を渡して位置情報(緯度経度)を得る処理である。例えば、http://maps.google.com/maps/api/geocode/xml?address=住所&sensor=falseのようなURLにアクセスすると、その住所に対応する位置情報を得ることができる。 レスポンスはJSON形式が推奨されているが、今回はXML形式を指定する。パラメータの最後のsensor=true or falseは必須である。ジオコーディングの詳細はこちらを参照していただきたい。
package biz.office_matsunaga.HttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HttpClientActivity extends Activity {
TextView textView3;
Button button1;
EditText editText1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView3 = (TextView)findViewById(R.id.textView3);
button1 = (Button)findViewById(R.id.button1);
editText1 = (EditText)findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView3.setText("");
HttpClient client = new DefaultHttpClient(); // HttpClientの生成
try {
// URLの生成
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/xml?address=" + editText1.getText() + "&language=ja&sensor=false");
HttpResponse httpResponse = client.execute(httpGet); // サーバにアクセス
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder response = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
textView3.setText(response.toString());
} else {
textView3.setText(httpResponse.getStatusLine().toString());
}
} catch (IOException e) {
textView3.setText(e.toString());
}
}
});
}
}
このサンプルではDefaultHttpClientを利用してジオコーディングリクエストを送信し、結果をXML形式のテキストで取得する。尚、このサンプルはインターネットにアクセスするので、予めAndroidManifest.xmlでINTERNETパーミッションを付与しておく必要がある。
ここで例えばeditTextに「東京駅」等と入力し、検索ボタンを押下すると結果がXMLで返される。「東京駅」が国外にも知られているためか結果は英語で返されるので、リクエストの際にlanguage=jaを指定している。指定した住所が正確でない場合、複数の結果が返されることがある。 (2012/01/23)
Copyright(C) 2004-2013 モバイル開発系(K) All rights reserved.
[Home]
|
|||||