public class HttpRequest {
	private static final int CONN_TIME_OUT = 2000 ;
	private static final int READ_TIME_OUT = 2000 ;
	private static final String HTTP = "http://" ;
	private URL url ;
	private HttpURLConnection conn ;
	public HttpRequest(String url){
		this(url, CONN_TIME_OUT, READ_TIME_OUT) ;
	}
	public HttpRequest(String url,int connTimeOut,int readTimeOut){
		if(url == null ||TextUtils.isEmpty(url)){ 
			throw new IllegalArgumentException("url is not empty" ) ;
		}
		if(!url.startsWith(HTTP)){
			url = HTTP + url ;
		}
		init(url,connTimeOut,readTimeOut); 
	}
	private void init(String url,int connTimeOut,int readTimeOut) {
		try {
			this.url = new URL(url) ;//使用URL字符串构建URL对象
			conn = (HttpURLConnection) this.url.openConnection() ;//通过URL对象获取和服务器的链接
			conn.setConnectTimeout(connTimeOut);//链接超时,单位毫秒
			conn.setReadTimeout(readTimeOut);//读超时,单位毫秒 
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public InputStream getInputStream() throws IOException{ 
		if( conn != null )
		return conn.getInputStream() ;
		return null ;
	}
	public String getData(){
		ByteArrayOutputStream baos = null ;
		InputStream inputStream = null ;
		try {
			inputStream = getInputStream() ;
			baos = new ByteArrayOutputStream() ;
			byte[] buffer = new byte[4096];
			int flag = -1 ;
			while(true){
				flag = inputStream.read(buffer, 0, 4096);
				if(flag == -1)break ;
				baos.write(buffer, 0, flag); 
			}
			return new String(baos.toByteArray()) ;
		} catch (IOException e) {
			return null ;
		}finally{
			release(inputStream,baos);
		}
	}
	public void release (Closeable... args){
		for (Closeable c : args) {
			if(c != null){
				try {
					c.close();
				} catch (IOException e) {
				} 
			}
		}
	}
	public void destory(){
		if(conn != null)
		conn.disconnect(); 
	}
}


Logo

openvela 操作系统专为 AIoT 领域量身定制,以轻量化、标准兼容、安全性和高度可扩展性为核心特点。openvela 以其卓越的技术优势,已成为众多物联网设备和 AI 硬件的技术首选,涵盖了智能手表、运动手环、智能音箱、耳机、智能家居设备以及机器人等多个领域。

更多推荐