Android開發 HTTP GET範例

巨人的肩膀

Android Asynchronous Http Client
A Callback-Based Http Client Library for Android
http://loopj.com/android-async-http/

build.gradle

dependencies {
    //...skip
    compile 'com.loopj.android:android-async-http:1.4.9'
}
`</pre>

Sync!!

### AndroidManifest.xml

<pre>`    &lt;uses-permission android:name="android.permission.INTERNET"/&gt;

    &lt;application
    //...skip
`</pre>

### 畫面配置

[![Screen Shot 2015-12-25 at 23.42.17](http://filitov.twcat.org/blog/wp-content/uploads/2015/12/Screen-Shot-2015-12-25-at-23.42.17-300x207.png)](http://filitov.twcat.org/blog/wp-content/uploads/2015/12/Screen-Shot-2015-12-25-at-23.42.17.png)

### 程式碼

<pre>`    public void btnClick( View view ){
        String url = ((EditText)findViewById(R.id.editText)).getText().toString();
        final TextView tv = (TextView)findViewById(R.id.textView);

        (new AsyncHttpClient()).get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                tv.setText(new String(responseBody, StandardCharsets.UTF_8));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }