トップ «前の日記(2009-11-19) 最新 次の日記(2009-11-25)» 編集

Ussy Diary


2009-11-23

[Android][Java]Android で HTTPS 通信をする

亀さんな開発速度でいじっています。今日は HTTPS 通信をやってみました。

コード前半にカスタマイズしたコードを入れていますが、 new DefaultHttpClient() で HTTPS 通信できます。カスタマイズする必要がなければ引数なしのコンストラクタを呼び出せば問題ありません。

SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.path("/login");

HttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
HttpPost post = new HttpPost(uriBuilder.build().toString());

List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
postParams.add(new BasicNameValuePair("id", username));
postParams.add(new BasicNameValuePair("password", password));

try {
    post.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
    HttpResponse httpResponse = client.execute(new HttpHost("example.com", 443, "https"), post);
    // レスポンスコードなど取得
} catch (ClientProtocolException e) {
    throw new RuntimeException(e);
} catch (IOException e) {
    throw new RuntimeException(e);
}

AndroidManifest.xml にインターネット接続を許可することを記述します。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
本日のツッコミ(全1件) [ツッコミを入れる]
# wontea (2011-12-29 16:20)

a.ri.ga.to