Http工具类

public class HttpUtile {

//单利模式 懒汉式


private MyHander myHander =new MyHander();
private HttpListener httpListener;
private static final String TAG = "HttpUtile";

private  static  HttpUtile httpUtile=new HttpUtile();
public static HttpUtile getHttpUtile() {
    if(httpUtile == null){
        httpUtile=new HttpUtile();
    }
    return httpUtile;
}
//封装get
public void get(final String url){
     new Thread(){
         @Override
         public void run() {
             super.run();
             try {
                 URL url1=new URL(url);
                 HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
                 connection.setConnectTimeout(3000);

                 if (connection.getResponseCode() == 200){
                     Log.d(TAG, "HttpUtile-------------- "+"请求成功");
                     InputStream inputStream = connection.getInputStream();
                     String json = Https.IntoString(inputStream);
                     Log.d(TAG, "HttpUtile-------------- "+json);
                     Message msg = myHander.obtainMessage();
                     msg.what=0;
                     msg.obj=json;
                   myHander.sendMessage(msg);
                 }else{
                     Log.d(TAG, "HttpUtile-------------- "+"请求失败");
                 }
             } catch (Exception e) {
                 e.printStackTrace();
                 Log.d(TAG, "HttpUtile-------------- "+e.getMessage());
             }
         }
     }.start();
}

 class MyHander extends Handler {
     @Override
     public void handleMessage(Message msg) {
         super.handleMessage(msg);
         switch (msg.what){
             case 0:
                 String json= (String) msg.obj;
                 httpListener.getDataSuccess(json);
                 break;
             case 1:
                 httpListener.getDataError("访问失败");
                 break;
         }
     }
 }

//回调
public interface HttpListener{
void getDataSuccess(String json);
void getDataError(String error);
}
public void getHttpListener(HttpListener httpListener){
this.httpListener =httpListener;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值