您的位置:首页 > 其它

AsyncTask的异步执行方法中get请求的方式

2017-09-04 20:11 260 查看
                    new AsyncTask<String, Integer, String>(){

              //一般基本最少写这俩种方法

//doInBackground 方法
@Override
protected String doInBackground(String... params) {
//打开连接
URL url;
String str="";
try {
url = new URL("https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10");

HttpURLConnection conne=(HttpURLConnection) url.openConnection();
                    //设置时间

Log.d("zzz", "走没走!!!!");
conne.setReadTimeout(5000);

conne.setConnectTimeout(5000);

int responseCode = conne.getResponseCode();

              //判断
if (responseCode==200) {

InputStream in = conne.getInputStream();
byte[] by=new byte[1024];
int len=0;

while ((len=in.read(by))!=-1) {

str+=new String(by,0,len);

}

}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return str;
}

                                //onPostExecute方法

protected void onPostExecute(String result) {
Log.d("zzz", result);
Gson gson = new Gson();
f = gson.fromJson(result, JsonRootBean.class);

data = f.getNewslist();
//适配器
Myadpader myadpader = new Myadpader(data, MainActivity.this);
list.setAdapter(myadpader);

super.onPostExecute(result);
};

//这一步必须要写execute()
}.execute();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: