Android Jamendo源码分析之 网络连接模块

江凯风
2023-12-01

程序中实现网络连接和获取网络数据是通过JamendoGet2Api这个接口中的方法实现的,他的实现类是JamendoGet2ApiImpl.这里就以getPopularAlbumsWeek()这个函数为例分析.

class JamendoGet2ApiImpl中 getPopularAlbumsWeek函数源码:

	@Override
	public Album[] getPopularAlbumsWeek() throws JSONException, WSError {
		
		String jsonString = doGet("id+name+url+image+rating+artist_name/album/json/?n=20&order=ratingweek_desc");
		if(jsonString == null)
			return null;
		JSONArray jsonArrayAlbums = new JSONArray(jsonString); 
		return AlbumFunctions.getAlbums(jsonArrayAlbums);
		
	}

首先通过doGet方法根据指定的url通过HTTP协议获取网络数据。

里面的 doGet函数 调用 Caller.doGet 函数返回网络数据。

Caller.get 函数源码:

public static String doGet(String url) throws WSError{
		
		String data = null;
		if(requestCache != null){
			data = requestCache.get(url);
			if(data != null){
				Log.d(JamendoApplication.TAG, "Caller.doGet [cached] "+url);
				return data;
			}
		}
		
		// initialize HTTP GET request objects
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse;
		
		try {
			// execute request
			try {
				httpResponse = httpClient.execute(httpGet);
			} catch (UnknownHostException e) {
				WSError wsError = new WSError();
				wsError.setMessage(e.getLocalizedMessage());
				throw wsError;
			} catch (SocketException e){
				WSError wsError = new WSError();
				wsError.setMessage(e.getLocalizedMessage());
				throw wsError;
			}
			
			// request data
			HttpEntity httpEntity = httpResponse.getEntity();
			
			if(httpEntity != null){
				InputStream inputStream = httpEntity.getContent();
				data = convertStreamToString(inputStream);
				// cache the result
				if(requestCache != null){
					requestCache.put(url, data);
				}
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Log.d(JamendoApplication.TAG, "Caller.doGet "+url);
		return data;
	}

根据返回的字符串数据创建JSONArray对象:

JSONArray jsonArrayAlbums = new JSONArray(jsonString); 

然后根据AlbumFunctions的静态函数getAlbums将封装在JSONArray中字符串数据转换为Album对象,然后放在数组中返回:

return AlbumFunctions.getAlbums(jsonArrayAlbums);

====================================================================================================

其中的 RequestCache类,类似一缓冲区

将访问数据,暂存于HashTable中,到需要访问一个url获取网络数据是,先到缓冲区中去查找,若查找到则直接返回,否则联网获取。              

 类似资料: