public class MainActivity extends AppCompatActivity { private TextView text_title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取控件 text_title = (TextView) findViewById(R.id.text_title); Mytask mytask = new Mytask(); mytask.execute(); } class Mytask extends AsyncTask<Void,Void,String>{ @Override protected String doInBackground(Void... voids) { try { //创建httpclient对象 DefaultHttpClient client = new DefaultHttpClient(); //路径 String path = "http://apis.juhe.cn/cook/query?key=?&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3"; //创建请求方式 HttpGet httpGet = new HttpGet(path); //用对象执行 HttpResponse execute = client.execute(httpGet); //获取状态码,要先获取状态行 int statusCode = execute.getStatusLine().getStatusCode(); if (statusCode == 200) { //获取实体内容 InputStream content = execute.getEntity().getContent(); //把实体内容转为字符串 InputStreamReader inputStreamReader = new InputStreamReader(content); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); //创建字符串缓冲区 StringBuilder builder = new StringBuilder(); //创建变量,用来存储读取的内容 String string = null; //循环读取内容 while ((string = bufferedReader.readLine()) != null) { builder.append(string); } bufferedReader.close(); return builder.toString(); } } catch (Exception e) { e.printStackTrace(); } return null; } //此方法接收doinbackground方法的返回值 @Override protected void onPostExecute(String s) { text_title.setText(s); } } }
Android中异步任务请求网络数据
最新推荐文章于 2024-07-21 21:22:17 发布