HttpURLConnection 用法

1.HttpURLConnection 获取服务端返回信息

 

 public  void  getInfo() throws IOException{
		
		String respContent = "" ;
		int code = 200;
		String geoUrl = "http://www.hao123.com/?tn=98012088_1_hao_pg";
	    URL url = new URL(geoUrl);
	    //返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		//设置一个指定的超时值(以毫秒为单位)
	 	httpURLConnection.setConnectTimeout(5*1000);
	 	//设置默认缓存
		httpURLConnection.setDefaultUseCaches(false);
		//URL 连接可用于输出,默认为 false
		httpURLConnection.setDoOutput(false); 
		//URL 连接可用于输入, 默认为TRUE
		httpURLConnection.setDoInput(true);
		//设置一般请求属性
		httpURLConnection.setRequestProperty("Charset", "UTF-8");
		//打开到此 URL 引用的资源的通信链接
	 	httpURLConnection.connect();
		if (httpURLConnection.getResponseCode() == 200){
			//连接读取的输入流
			InputStream inputStream = httpURLConnection.getInputStream(); 
			byte[] bytes = new byte[8024];  
			ByteArrayOutputStream bos = new ByteArrayOutputStream();  
			int count = 0;  
			while((count = inputStream.read(bytes))!= -1){  
				bos.write(bytes, 0, count);  
			}  
			byte[] strByte = bos.toByteArray();  
			respContent = new String(strByte,0,strByte.length,"utf-8");  
			//关闭 
			bos.close();
			inputStream.close();    
			httpURLConnection.disconnect();
		 }
		else{
			 
		    code = httpURLConnection.getResponseCode();
			
		}
	   System.out.println(code+"返回内容为:"+respContent);
	    
		 
  
	}


 

你可能感兴趣的:(java)