Android:漫画APP开发笔记之从WAP网站解析图片地址并加载图片

一、使用Jsoup解析网页

<pre><code class="prettyprint"><span class="typ">Document</span><span class="pln"> doc </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Jsoup</span><span class="pun">.</span><span class="pln">connect</span><span class="pun">(</span><span class="str">url</span><span class="pun">).</span><span class="kwd">get</span><span class="pun">();</span><span class="pln">
</span></code>

 

二、Session保持

在项目中,通过浏览器访问网址点击“下一页”能正常翻页,而Android客户端每次GET的“下一页”地址都是第一页。原来是因为android客户端向网站发送HTTP请求时,没有在请求头部设置JSESSIONID,而使用浏览器访问服务器时,在客户端每次发起请求的时候,都会将JSESSIONID设置在Cookie头中携带过去。因此可以在第一次数据请求时就获取sessionid的值并保存在一个静态变量中,然后将其打包在后续HTTP请求的Cookie中发给服务器,服务器根据这个JSESSIONID获取对应的Session,而不是重新创建一个新Session。当然,也可以直接将第一次数据请求时获取的cookies整个打包回去:

<span style="font-size:12px;"></span><pre name="code" class="java"><span style="font-size:12px;">Connection.Response res= Jsoup.connect(url)
		         .method(Method.GET)
			 .execute();</span>
Document doc= Jsoup.connect(url) .cookies(res.cookies()) .timeout(10000) .get();

 

三、标签解析

由于项目网站所需要解析的图片标签特有width=100%这种属性,因此可通过以下方式解析出图片地址并加载图片:

<span style="font-size:12px;"> Elements element = doc.select("img").select("[width=100%]"); // 具有 href 属性的链接
     	      Log.d("element", element.toString());
     	      for(Element links : element)
     	      { 
     	    	  String link  = links.attr("src");
     	    	  try {
     	    		  myFileUrl = new URL(link);
     	    	  } catch (MalformedURLException e) {
     	    		 Log.i("msg", "没有数据");
     	    	  }
     	    	  try {
     	    		   HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
     	    		   conn.setConnectTimeout(0);
     	                   conn.setDoInput(true);
     	                   conn.connect();
     	                   InputStream is = conn.getInputStream();
     	                   bitmap = BitmapFactory.decodeStream(is);
     	                   is.close();
     	          } catch (IOException e) {
     	        	 Log.i("msg", "没有数据");
     	          }
     	                   PicListInfo pi = new PicListInfo();
     	                   pi.setPicUrl(bitmap);
     	                   newpiclistinfo.add(0,pi);                    
     	          }
	</span>

四、listview+adapter显示图片

<span style="font-size:12px;">if(newpiclistinfo.size() > 0){
			Collections.reverse(newpiclistinfo);
		        piclistinfo.addAll(newpiclistinfo);
			sla.notifyDataSetChanged();	
			piclist.setDividerHeight(0);
			if(dlg_loading.isShowing()){
			dlg_loading.cancel();
			}
			}else
			{
				Log.i("msg", "没有数据");
			}
		  </span>
由于网站每页只显示4张图片,一共有8页,因此在加载完前四张后需要保持session并模拟浏览器的“翻页”:

<span style="font-size:12px;">if(count<8){
		      Element next=doc.getElementById("toNext");
		      String next_url=next.attr("href");//“下一页”的url
		      getpic(next_url);//调用图片加载的异步线程
		      }
		   else{
			   Log.i("msg", "加载完毕");
			   Toast.makeText(getApplicationContext(), "已全部加载",
			    		  Toast.LENGTH_SHORT).show();
		   }</span>
附图片加载的完整线程:

<span style="font-size:12px;">	public void getpic(String url){
		new HTMLAsyncTask().execute(url);	
	}
 private class HTMLAsyncTask extends AsyncTask<String, Integer, ArrayList<PicListInfo>> {
    	 Document doc = null;
    protected ArrayList<PicListInfo> doInBackground(String... Urls) {
    	 URL myFileUrl = null;
         Bitmap bitmap = null;      
         ArrayList<PicListInfo> newpiclistinfo = new ArrayList<PicListInfo>();
    	try {	
    		String test=res.cookies().toString();
    		doc= Jsoup.connect(Urls[0])
       	   			 .cookies(res.cookies())
       	   			 .timeout(10000)
       	   			 .get(); 
     	      Elements element = doc.select("img").select("[width=100%]"); // 具有 href 属性的链接
     	      Log.d("element", element.toString());
     	      for(Element links : element)
     	      { 
     	    	  String link  = links.attr("src");
     	    	  try {
     	    		  myFileUrl = new URL(link);
     	    	  } catch (MalformedURLException e) {
     	    		 Log.i("msg", "没有数据");
     	    	  }
     	    	  try {
     	    		   HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
     	    		   conn.setConnectTimeout(0);
     	               conn.setDoInput(true);
     	               conn.connect();
     	               InputStream is = conn.getInputStream();
     	               bitmap = BitmapFactory.decodeStream(is);
     	               is.close();
     	          } catch (IOException e) {
     	        	 Log.i("msg", "没有数据");
     	          }
     	              PicListInfo pi = new PicListInfo();
     	              pi.setPicUrl(bitmap);
     	              newpiclistinfo.add(0,pi);                    
     	          }
	
        }catch (IOException e) {
			// TODO Auto-generated catch block
        	Log.i("msg", "没有数据");
		}
    	
		return newpiclistinfo;
            
    }
    // 异步方法调用对返回的字符串进行处理
    protected void onPostExecute(ArrayList<PicListInfo> newpiclistinfo) {
      try {
		count++;	
		  if(newpiclistinfo.size() > 0){
			Collections.reverse(newpiclistinfo);
		    piclistinfo.addAll(newpiclistinfo);
			sla.notifyDataSetChanged();	
			piclist.setDividerHeight(0);
			if(dlg_loading.isShowing()){
			dlg_loading.cancel();
			}
			}else
			{
				Log.i("msg", "没有数据");
			}
		  
		   if(count<8){
		      Element next=doc.getElementById("toNext");
		      String next_url=next.attr("href");
		      getpic(next_url);
		      }
		   else{
			   Log.i("msg", "加载完毕");
			   Toast.makeText(getApplicationContext(), "已全部加载",
			    		  Toast.LENGTH_SHORT).show();
		   }
	} catch (Exception e) {
		Toast.makeText(getApplicationContext(), "网络连接出错啦",
    		  Toast.LENGTH_SHORT).show();
	}
			                 
    }
       } </span>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值