写工具类方便多次调用
public class JavaUtils {
public String getString(String surl){
String str="";
try {
URL url = new URL(surl);
HttpURLConnection http=(HttpURLConnection) url.openConnection();
int code = http.getResponseCode();
if(code==200){
InputStream in = http.getInputStream();
byte[] b=new byte[1024];
int len=0;
while((len=in.read(b))!=-1){
str+=new String(b,0,len);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
异步任务的使用(AsyncTask)
new AsyncTask<String,Integer,String>(){
@Override
protected String doInBackground(String... strings) {
String string = new JavaUtils().getString("http://gank.io/api/data/"+st+"/10/"+"1");
return string;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
new Gson().fromJson(s, JavaBean.class);
}
}.execute();