zoukankan      html  css  js  c++  java
  • Android 图文数据JSON解析,金山词霸每日一句API的调用

    金山词霸开发的免费API http://open.iciba.com/dsapi/

    数据格式为

    {"sid":"737",
    "tts":"http://news.iciba.com/admin/tts/2013-12-11.mp3",
    "content":"I don't want us to be together because we have to,I want us to be together because we want to.",
    "
    note":"u6211u4e0du5e0cu671bu6211u4eecu56e0u4e3au201cu4e0du5f97u4e0du201du800cu5728u4e00u8d77uff0cu6211u5e0cu671bu6211u4eecu662fu56e0u4e3au60f3u5728u4e00u8d77u800cu5728u4e00u8d77u3002",
    "translation":"u611fu8c22@u7a0bu5f88u591au8981u79d2u8650u6570u5b66 u6295u7a3fu3002u8bcdu9738u5c0fu7f16uff0cu8fd9u53e5u8bddu6765u81eau300au51b0u6cb3u4e16u7eaa2u300buff0cu662fu4e00u4e2au7cfbu5217u7684u52a8u753bu7535u5f71uff0cu975eu5e38u641eu7b11uff0cu4f60u770bu8fc7u5417uff1f",
    "picture":"http://cdn.iciba.com/news/word/2013-12-11.jpg","picture2":"http://cdn.iciba.com/news/word/big_2013-12-11b.jpg","caption":"u8bcdu9738u6bcfu65e5u4e00u53e5",
    "dateline":"2013-12-11",
    "
    s_pv":"8693",
    "
    sp_pv":"2090",
    "
    tags":[{"id":"9","name":"u7231u60c5"},{"id":"14","name":"u7535u5f71u7ecfu5178"}],
    "fenxiang_img":"http://cdn.iciba.com/web/news/longweibo/imag/2013-12-11.jpg"}

    JSON字段解释

    JSON 字段解释
    {
    'sid':'' #每日一句ID
    'tts': '' #音频地址
    'content':'' #英文内容
    'note': '' #中文内容
    'translation':'' #词霸小编
    'picture': '' #图片地址
    'picture2': '' #大图片地址
    'caption':'' #标题
    'dateline':'' #时间
    's_pv':'' #浏览数
    'sp_pv':'' #语音评测浏览数
    'tags':'' #相关标签
    'fenxiang_img':'' #合成图片,建议分享微博用的
    }

    最终实现的效果

    具体实现,使用AsynTask异步访问网络:

    class Load extends AsyncTask<String, String, String>
        {
            public String url = "http://open.iciba.com/dsapi/";
            ProgressDialog pdlg;
            String jsonstr = "";
            JSONObject json = null;
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                try{
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(url);
                    HttpResponse httpResponse = httpClient.execute(httppost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    InputStream is = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "
    ");
                    }
                    is.close();
                    jsonstr = sb.toString();
                    json = new JSONObject(jsonstr.toString());
                    engstr = json.getString("content");
                    chistr = json.getString("note");
                    imagurl = json.getString("picture");
                    timestr =    json.getString("dateline");
                    fromstr   =  json.getString("translation");
                    JSONArray array = json.getJSONArray("tags");
                    for(int i=0;i<array.length();i++)
                    {
                        JSONObject tag = (JSONObject)array.get(i);
                        tagstr += tag.getString("name")+"," ; 
                    }
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
                
                return null;
            }
    
            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                pdlg.dismiss();
                imageLoader.DisplayImage(imagurl,imageview);
                eng.setText("    "+engstr);
                chi.setText("    "+chistr);
                tag.setText(tagstr);
                time.setText(timestr);
                from.setText("    "+fromstr);
            }
    
            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                pdlg = new ProgressDialog(context);
                pdlg.setCancelable(false);
                pdlg.setMessage("正在加载");
                pdlg.show();
            }
        }

    使用了一个图片处理的工具类,ImageLoader,主要用来通过url解析图片,处理图片的大小,以文件的形式缓存图片。

    public class ImageLoader {
        
        MemoryCache memoryCache=new MemoryCache();
        FileCache fileCache;
        private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
        ExecutorService executorService; 
        
        public ImageLoader(Context context){
            fileCache=new FileCache(context);
            executorService=Executors.newFixedThreadPool(5);
        }
        
        final int stub_id = R.drawable.drug_trans;
        public void DisplayImage(String url, ImageView imageView)
        {
            imageViews.put(imageView, url);
            Bitmap bitmap=memoryCache.get(url);
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
            {
                queuePhoto(url, imageView);
                imageView.setImageResource(stub_id);
            }
        }
            
        private void queuePhoto(String url, ImageView imageView)
        {
            PhotoToLoad p=new PhotoToLoad(url, imageView);
            executorService.submit(new PhotosLoader(p));
        }
        
        private Bitmap getBitmap(String url) 
        {
            File f=fileCache.getFile(url);
            
            //from SD cache
            Bitmap b = decodeFile(f);
            if(b!=null)
                return b;
            
            //from web
            try {
                Bitmap bitmap=null;
                URL imageUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
                conn.setConnectTimeout(30000);
                conn.setReadTimeout(30000);
                conn.setInstanceFollowRedirects(true);
                InputStream is=conn.getInputStream();
                OutputStream os = new FileOutputStream(f);
                Utils.CopyStream(is, os);
                os.close();
                bitmap = decodeFile(f);
                return bitmap;
            } catch (Exception ex){
               ex.printStackTrace();
               return null;
            }
        }
    
        //decodes image and scales it to reduce memory consumption
        private Bitmap decodeFile(File f){
            try {
                //decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f),null,o);
                
                //Find the correct scale value. It should be the power of 2.
                final int REQUIRED_SIZE=70;
                int width_tmp=o.outWidth, height_tmp=o.outHeight;
                int scale=1;
                while(true){
                    if(width_tmp/1.5<REQUIRED_SIZE || height_tmp/1.5<REQUIRED_SIZE)
                        break;
                    width_tmp/=1.5;
                    height_tmp/=1.5;
                    scale*=1.5;
                }
                
                //decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize=scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {}
            return null;
        }
        
        //Task for the queue
        private class PhotoToLoad
        {
            public String url;
            public ImageView imageView;
            public PhotoToLoad(String u, ImageView i){
                url=u; 
                imageView=i;
            }
        }
        
        class PhotosLoader implements Runnable {
            PhotoToLoad photoToLoad;
            PhotosLoader(PhotoToLoad photoToLoad){
                this.photoToLoad=photoToLoad;
            }
            
            @Override
            public void run() {
                if(imageViewReused(photoToLoad))
                    return;
                Bitmap bmp=getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if(imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
                Activity a=(Activity)photoToLoad.imageView.getContext();
                a.runOnUiThread(bd);
            }
        }
        
        boolean imageViewReused(PhotoToLoad photoToLoad){
            String tag=imageViews.get(photoToLoad.imageView);
            if(tag==null || !tag.equals(photoToLoad.url))
                return true;
            return false;
        }
        
        //Used to display bitmap in the UI thread
        class BitmapDisplayer implements Runnable
        {
            Bitmap bitmap;
            PhotoToLoad photoToLoad;
            public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
            public void run()
            {
                if(imageViewReused(photoToLoad))
                    return;
                if(bitmap!=null)
                    photoToLoad.imageView.setImageBitmap(bitmap);
                else
                    photoToLoad.imageView.setImageResource(stub_id);
            }
        }
    
        public void clearCache() {
            memoryCache.clear();
            fileCache.clear();
        }
    
    }
  • 相关阅读:
    IE10、IE11下SCRIPT5009: “__doPostBack”未定义
    CSS Hack大全-可区分出IE6-IE10、FireFox、Chrome、Opera
    HTML head 头标签
    html5匹配不同分辨率样式
    html5关键帧动画,一个小例子快速理解关键帧动画
    导入Excel到数据库
    JavaScript树(一) 简介
    深入解析浏览器的幕后工作原理(五) 呈现树
    深入解析浏览器的幕后工作原理(四) DOM树
    深入解析浏览器的幕后工作原理(三) 呈现树和 DOM 树的关系
  • 原文地址:https://www.cnblogs.com/LIANQQ/p/3470006.html
Copyright © 2011-2022 走看看