public class HttpUtils {
private static HttpUtils httpUtils;
private getjsondata getjsondata;
private Handler handler =new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==0){
String json =(String)msg.obj;
getjsondata.getshuju(json); //在这里发送消息
}
}
};
//单例
public static HttpUtils getinstace(){
if(httpUtils==null){
httpUtils =new HttpUtils();
}
return httpUtils;
}
//方法
public void getdata(final String path){
new Thread(){
@Override
public void run() {
super.run();
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
if(connection.getResponseCode()==200){
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
bos.write(bytes,0,len);
}
inputStream.close();
bos.close();
String json = bos.toString();
Message message = new Message(); //重点强调最后四步,创建消息和标识,并发送
message.what=0;
message.obj=json;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
//接口
public interface getjsondata{
public void getshuju(String json);
}
//接口向外调用
public void setjsondata(getjsondata getjsondata){
this.getjsondata =getjsondata;
}
}