android-async-http get 请求Json数据

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


你可能感兴趣的:(android-async-http get 请求Json数据)