3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Android]AndroidHttpClientがNGになっていたので、HttpURLConnectionでアクセスしてみた

Posted at

AndroidHttpClientを利用しようとすると利用してはいけないと怒られてしまうので、
HttpURLConnectionを使ってHttp通信を行いました。
今回はヘッダー領域はいらないのでページの内容だけを取得するクラスです。

参考:
Android’s HTTP Clients
http://android-developers.blogspot.jp/2011/09/androids-http-clients.html

HttpURLConnectionを使用してHTTP通信を行う
http://techbooster.jpn.org/andriod/application/6812/

HttpClient.java
public class HttpClient {
    private HttpURLConnection connection = null;

    public String get(String url){
        String pageData = "";
        try {
            URL u = new URL(url);
            connection = (HttpURLConnection)u.openConnection();
            connection.setRequestMethod("GET");
            connection.setInstanceFollowRedirects(false);
            connection.connect();

            InputStream is = connection.getInputStream();
            pageData = // ストリームの内容を転記;
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return pageData;
    }
}

URLやHttpURLConnectionのインスタンスを再利用できないかあれこれ頑張ろうとしましたが、
少なくともHttpURLConnectionはインスタンスの再利用はできないようです。
それと非同期でないため注意してください。

// 使い方
HttpClient client = new HttpClient();
String page = client.get("http://localhost:8080/index.html")
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?