android-async-http get 请求Json数据

作者: RickGe | 来源:发表于2016-12-13 12:35 被阅读360次

    01 添加Android-async-http

    compile 'com.loopj.android:android-async-http:1.4.9'
    

    02 网络请求class:ApiHttpClient

    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    
    public class ApiHttpClient {
        private static volatile ApiHttpClient client = null;
        private AsyncHttpClient asyncHttpClient = null;
    
        private ApiHttpClient(){
            asyncHttpClient = new AsyncHttpClient();
        }
    
        public static ApiHttpClient getInstance(){
            if(client == null){
                synchronized (ApiHttpClient.class){
                    if(client == null){
                        client = new ApiHttpClient();
                    }
                }
            }
            return client;
        }
    
        public void get(String url, AsyncHttpResponseHandler handler){
            asyncHttpClient.get(url, handler);
        }
    }
    

    03 MainActivity

    public class MainActivity extends AppCompatActivity {
        ApiHttpClient mClient = null;
        TextHttpResponseHandler mHandler = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initData();
        }
    
        private void initData() {
            mClient = ApiHttpClient.getInstance();
            mHandler = new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    Log.i("MainActivity", "Failure");
                }
    
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    Log.i("MainActivity", responseString);
                }
            };
    
            String url = "http://192.168.1.5:8080/tweet/tweet_new_01.json";
            mClient.get(url, mHandler);
        }
    }
    

    04 permission

    <uses-permission android:name="android.permission.INTERNET"/>
    

    相关文章

      网友评论

        本文标题:android-async-http get 请求Json数据

        本文链接:https://www.haomeiwen.com/subject/qiavmttx.html