public class Http<T> extends AsyncTask<String,Void,T> {
private OnResponseListener<T> listener;
public void setListener(OnResponseListener<T> listener) {
this.listener = listener;
}
@Override
protected T doInBackground(String... params) {
return null;
}
@Override
protected void onPostExecute(T t) {
super.onPostExecute(t);
if (listener!=null){
listener.onResponse(t);
}
}
//接口 类似一个监听事件
public interface OnResponseListener<T>{
void onResponse(T t);
}
}
//获取数据的测试类
public class Test {
//要获取的user对象
private User user1=null;
public void get(){
//创建网络访问实例
Http<User> http=new Http<User>();
//重写接口
http.setListener(new Http.OnResponseListener<User>() {
@Override
public void onResponse(User user) {
user1=user;
}
});
http.execute("xxx.balabala.com");
}
}
protected T doInBackground(String... params) {
//网络连接对象
HttpURLConnection connection=null;
//输入流 获取网络数据
InputStream is=null;
//字节数组输出流
ByteArrayOutputStream bos=null;
try {
//获取网络连接对象
connection=(HttpURLConnection) new URL(params[0]).openConnection();
//设置get请求 必须大写
connection.setRequestMethod("GET");
//获取网络请求码 200 400 500之类 不懂百度
int code=connection.getResponseCode();
if(code==200){
//获取流
is=connection.getInputStream();
//临时字节数组
byte [] b=new byte[1024];
int len=-1;
bos=new ByteArrayOutputStream();
while ((len=is.read(b))!=-1){
//写入数据
bos.write(b,0,len);
}
String json=bos.toString("utf-8");
T t=JSON.parseObject(json,type);
return t;
}else{
Log.e("error","网络访问失败==========="+code);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (bos!=null){
bos.close();
}
if (is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection!=null){
connection.disconnect();
}
}
return null;
}
protected T doInBackground(String... params) {
//分割url 分为地址和参数两部分
String[] strArr=params[0].split("\\?");
HttpURLConnection connection=null;
//输出流
OutputStream os=null;
//输入流
InputStream is=null;
ByteArrayOutputStream bos=null;
try {
connection=(HttpURLConnection) new URL(strArr[0]).openConnection();
connection.setRequestMethod("POST");
//设置允许输入 输出 默认值true 不写也可以
connection.setDoOutput(true);
connection.setDoInput(true);
os=connection.getOutputStream();
//把参数写入
os.write(strArr[1].getBytes("utf-8"));
os.close();
int code=connection.getResponseCode();
if(code==200){
is=connection.getInputStream();
byte [] b=new byte[1024];
int len=-1;
bos=new ByteArrayOutputStream();
while ((len=is.read(b))!=-1){
bos.write(b,0,len);
}
String json=bos.toString("utf-8");
T t=JSON.parseObject(json,type);
return t;
}else{
Log.e("error","网络访问失败==========="+code);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (bos!=null){
bos.close();
}
if (is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection!=null){
connection.disconnect();
}
}
return null;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有