//使用HttpURLConnection get 实现网络数据请求
public class HttpUtils {
private static final String TAG = "HttpUtils----";
//单利模式
private static HttpUtils httpUtils = new HttpUtils();
private final static int SUCCESS = 0;
private final static int ERROR = 1;
private MyHandler myHandler = new MyHandler();
private HttpUtilsListener httpUtilsListener;
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 url1 = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setConnectTimeout(3000);
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
//inputstream--string
String json = inputStreamToString(inputStream);
//发送
Message message = myHandler.obtainMessage();
message.what = SUCCESS;
message.obj = json;
myHandler.sendMessage(message);
} else {
Message message = myHandler.obtainMessage();
message.what = ERROR;
message.obj = "失败";
myHandler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
Message message = myHandler.obtainMessage();
message.what = ERROR;
message.obj = e.getMessage();
myHandler.sendMessage(message);
}
}
}.start();
}
//使用Handler 处理线程问题
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
//成功
String json = (String) msg.obj;
Log.d(TAG, "handleMessage: " + json);
//使用回调
httpUtilsListener.getDataSuccess(json);
break;
case ERROR:
//成功
String error = (String) msg.obj;
Log.d(TAG, "handleMessage: " + error);
//使用回调
httpUtilsListener.getDataError(error);
break;
}
}
}
public String inputStreamToString(InputStream inputStream) throws IOException {
int len = 0;
byte[] butter = new byte[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((len = inputStream.read(butter)) != -1) {
String s = new String(butter, 0, len);
stringBuffer.append(s);
}
return stringBuffer.toString();
}
//接口回调
public interface HttpUtilsListener {
void getDataSuccess(String json);
void getDataError(String error);
}
//外部访问的方法
public void setHttpUtilsListener(HttpUtilsListener httpUtilsListener) {
this.httpUtilsListener = httpUtilsListener;
}
}