import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; import android.util.Log; import com.google.gson.Gson; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import bwei.com.day_0517_123.adapter.MyBase; import bwei.com.day_0517_123.bean.SheHuiBean; public class HttpUtils { private static final String TAG = "HttpUtils-----"; private static final int SUCCESS = 0; private static final int ERROR = 1; private HttpUtilListener httpUtilListener; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SUCCESS: String json = (String) msg.obj; Log.d(TAG, "handleMessage: "+json); httpUtilListener.getSuccess(json); break; case ERROR: String error= (String) msg.obj; Log.d(TAG, "handleMessage: "+error); httpUtilListener.getError(error); break; } } }; //单利模式 private static HttpUtils httpUtils = new HttpUtils(); //无参构造 private HttpUtils() { } public static HttpUtils getInstance() { if (httpUtils == null) { httpUtils = new HttpUtils(); } return httpUtils; } //封装get public void get(final String url) { //开启线程 new Thread() { @Override public void run() { try { URL u = new URL(url); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.setConnectTimeout(5000); if (con.getResponseCode() == 200) { InputStream inputStream = con.getInputStream(); String json = ConUtils.in(inputStream); Log.d(TAG, "网络请求成功:!!!!!!!!!!!!!!!!!!!"+json); //发送消息 Message me = new Message(); me.what = SUCCESS; me.obj = json; //发送hanlder请求 handler.sendMessage(me); } } catch (Exception e) { e.printStackTrace(); Message m = new Message(); m.what = ERROR; m.obj = e.getMessage(); //发送handler请求 handler.sendMessage(m); } } }.start(); } //定义接口 public interface HttpUtilListener { void getSuccess(String json); void getError(String error); } //设置外部访问的方法 public void setHttpUtilsListener(HttpUtilListener httpUtilsListener) { this.httpUtilListener = httpUtilsListener; } }
这是一个Android平台下的HttpUtils工具类实现,使用HttpURLConnection进行网络请求。类中包含了一个内部Handler用于处理请求的成功和错误回调,同时定义了一个HttpUtilListener接口来供外部接收网络请求的结果。
1538

被折叠的 条评论
为什么被折叠?



