📜  如何使用异步任务进行api连接java代码示例

📅  最后修改于: 2022-03-11 14:52:04.312000             🧑  作者: Mango

代码示例1
class JSONAsyncTask extends AsyncTask {


@Override
protected void onPreExecute() {
    super.onPreExecute();

}

@Override
protected Boolean doInBackground(String... urls) {
    try {

        //------------------>>
        HttpGet httppost = new HttpGet("YOU URLS TO JSON");
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);

        // StatusLine stat = response.getStatusLine();
        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);


            JSONObject jsono = new JSONObject(data);

            return true;
        }


    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {

        e.printStackTrace();
    }
    return false;
}

protected void onPostExecute(Boolean result) {

}