2016年11月6日日曜日

AscnyTask 练习

AscnyTask 练习



public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //设置一个下载进度条
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(0);
        pd.setTitle("Downloadnow");

        //设置响应事件
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(this);
        Button bt2 = (Button) findViewById(R.id.button2);
        bt2.setOnClickListener(this);
        Button bt3 = (Button) findViewById(R.id.button3);
        bt3.setOnClickListener(this);
        Button bt4 = (Button) findViewById(R.id.button4);
        bt4.setOnClickListener(this);
        Button bt5 = (Button) findViewById(R.id.button5);
        bt5.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Img i = new Img();
        System.out.println(v.getId());
        switch (v.getId()) {
            case R.id.button:
                i.execute("http://image.i-voce.jp/files/article/main/s8AO3sFN_1438142266.jpg");
                break;
            case R.id.button2:
                i.execute("http://pic.prepics-cdn.com/d75526b7cc13/41938040.jpeg");
                break;
            case R.id.button3:
                i.execute("http://entertainment.rakuten.co.jp/movie/interview/kiritanimirei/img/interviewimg001.jpg");
                break;
            case R.id.button4:
                i.execute("http://up.gc-img.net/post_img_web/2015/09/32f61210611d358bddc2784d875cf65e_4238.jpeg");
                break;
            case R.id.button5:
                i.execute("http://lwoyr.com/wp-content/uploads/2015/06/20150618_5.jpg");
                break;
        }
    }

    public class Img extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            byte[] reBate = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setConnectTimeout(3000);
                huc.setReadTimeout(3000);
                huc.setDoInput(true);
                huc.setRequestMethod("GET");

                //用文件长度设置进度条的最大值
                pd.setMax(huc.getContentLength());
                if (huc.getResponseCode() == 200) {
                    InputStream is = huc.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        baos.write(buf, 0, len);
                        publishProgress(baos.size());
                    }
                    reBate = baos.toByteArray();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return reBate;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            ImageView iv = (ImageView) findViewById(R.id.imageView2);
            iv.setImageBitmap(bitmap);
            pd.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pd.setProgress(values[0]);
        }
    }
}

Android AsyncTask 异步任务下载图片并显示咋UI线程

Android AsyncTask 异步任务下载图片并显示咋UI线程



public class MainActivity extends AppCompatActivity {
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv = (ImageView) findViewById(R.id.imageView);
                DownImg di = new DownImg(MainActivity.this, iv);
                di.execute("url");
            }
        });
    }
}



public class DownImg extends AsyncTask<String, Integer, byte[]> {
    private ImageView iv;
    private int file_length;
    private Context context;
    protected ProgressDialog pd;

    public DownImg(Context context, ImageView iv) {
        this.iv = iv;
        this.context = context;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        ByteArrayOutputStream bos = null;
        try {
            URL url = new URL("http://prw.kyodonews.jp/prwfile/release/M102245/201403149047/_prw_PI1fl_2o2KuN2D.jpg");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            file_length = httpURLConnection.getContentLength();
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = httpURLConnection.getInputStream();
                bos = new ByteArrayOutputStream();
                byte[] buff =  new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    bos.write(buff, 0, len);
                    publishProgress(file_length,bos.size());
                }
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toByteArray();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setTitle("test");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        pd.setMax(100);
        pd.setProgress(0);
        pd.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        pd.setMax(values[0]);
        pd.setProgress(values[1]);
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        Bitmap bt = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        iv.setImageBitmap(bt);
        pd.dismiss();
    }
}



2016年11月4日金曜日

Android JSONObject 练习

Android JSONObject 练习

1.  JSON链接
     http://cdefgab.web.fc2.com/song.json


public class DownJson {

    public void ejson() {
        String data = jsonString();
        HashMap<String, String> hh = new HashMap<String, String>();
        HashMap<Integer, HashMap<String, String>> hl = new HashMap<Integer, HashMap<String, String>>();

        try {
            JSONObject js = new JSONObject(data);
            JSONObject js2 = js.getJSONObject("photos");
            hh.put("stat", js.getString("stat"));
            hh.put("page", js2.getString("page"));
            hh.put("pages", js2.getString("pages"));
            hh.put("perpage", js2.getString("perpage"));
            hh.put("total", js2.getString("total"));

            String ja = js2.getString("photo");
            JSONArray jaa = new JSONArray(ja);

            for (int i = 0; i < jaa.length(); i++) {
                JSONObject t1 = jaa.getJSONObject(i);
                HashMap<String, String> hmt = new HashMap<String, String>();
                hmt.put("id", t1.getString("id"));
                hmt.put("owner", t1.getString("owner"));
                hmt.put("secret", t1.getString("secret"));
                hmt.put("server", t1.getString("server"));
                hmt.put("farm", t1.getString("farm"));
                hmt.put("title", t1.getString("title"));
                hmt.put("ispublic", t1.getString("ispublic"));
                hmt.put("isfriend", t1.getString("isfriend"));
                hmt.put("isfamily", t1.getString("isfamily"));
                hl.put(i, hmt);
            }

            System.out.println("-----------------------");
            System.out.println(hl.get(0).get("title"));
            System.out.println("-----------------------");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public static String jsonString() {
        String jstring = null;
        InputStream is = null;
        try {
            URL u = new URL("http://cdefgab.web.fc2.com/song.json");
            HttpURLConnection h = (HttpURLConnection) u.openConnection();
            h.setRequestMethod("GET");
            h.setDoInput(true);
            h.setConnectTimeout(3000);
            h.setReadTimeout(3000);
            if (h.getResponseCode() == 200) {
                byte[] buff = new byte[1024];
                int len = 0;
                is = h.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = is.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                jstring = baos.toString("utf-8");
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jstring;
    }
}


2016年11月2日水曜日

ByteArrayOutputStream 练习

ByteArrayOutputStream 练习


import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) throws Exception {

    // https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be
    // https://images-na.ssl-images-amazon.com/images/I/81M-I12yh7L._SL1500_.jpg
    // http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip
    // http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip
    // http://cdefgab.web.fc2.com/song.json

    httpd h = new httpd("http://cdefgab.web.fc2.com/song.json");
    h.std();
    }
}

class httpd{
    private String durl;
 
    public httpd(String durl){
        this.durl = durl;
    }

    public void std(){
        System.out.println("sdt()-start");
        try{
        FileOutputStream fis = new FileOutputStream("demo.db");
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        InputStream is = dis();
        byte[] buff = new byte[10240];
        int len = 0;
     
        System.out.println("koko");
        while( (len = is.read(buff)) != -1){
            fis.write(buff,0,len);
            fis.flush();
            bao.write(buff,0,len);
            System.out.println(len);
        }
     
        fis.close();
        System.out.println(bao.toString());
        }catch(Exception e){
         
        }finally{
            File f = new File("demo.db");
            System.out.println(f.getName());
            System.out.println(f.getAbsolutePath());
        }
    }

    public InputStream dis(){
        InputStream inputStream = null;
        try{
            URL url = new URL(durl);
            System.out.println("url = " + durl);
            HttpURLConnection httpurl = (HttpURLConnection)url.openConnection();
            httpurl.setConnectTimeout(3000);
            httpurl.setDoInput(true);
            httpurl.setReadTimeout(3000);
            httpurl.setRequestMethod("GET");
            if(httpurl.getResponseCode() == 200){
                System.out.println("paus" + httpurl.getResponseCode());
                inputStream = httpurl.getInputStream();
            }
        }catch(Exception e){
        }
        return inputStream;
    }
}

2016年11月1日火曜日

HttpFileDownload 练习

HttpFileDownload 练习

https://paiza.io/projects/6lTQWbqAzvT-IEAHaRl4AA



import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) throws Exception {

    // https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be
    // https://images-na.ssl-images-amazon.com/images/I/81M-I12yh7L._SL1500_.jpg
    // http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip

    httpd h = new httpd("https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be");
    h.std();
    }
}

class httpd{
    private String durl;
   
    public httpd(String durl){
        this.durl = durl;
    }

    public void std(){
        System.out.println("sdt()-start");
        try{
        FileOutputStream fis = new FileOutputStream("demo.db");
        InputStream is = dis();
        byte[] buff = new byte[10240];
        int len = 0;
       
        System.out.println("koko");
        while( (len = is.read(buff)) != -1){
            fis.write(buff,0,len);
            fis.flush();
            System.out.println(len);
        }
       
        fis.close();
        }catch(Exception e){
           
        }finally{
            File f = new File("demo.db");
            System.out.println(f.getName());
            System.out.println(f.getAbsolutePath());
        }
    }

    public InputStream dis(){
        InputStream inputStream = null;
        try{
            URL url = new URL(durl);
            System.out.println("url = " + durl);
            HttpURLConnection httpurl = (HttpURLConnection)url.openConnection();
            httpurl.setConnectTimeout(3000);
            httpurl.setDoInput(true);
            httpurl.setReadTimeout(3000);
            httpurl.setRequestMethod("GET");
            if(httpurl.getResponseCode() == 200){
                System.out.println("paus" + httpurl.getResponseCode());
                inputStream = httpurl.getInputStream();
            }
        }catch(Exception e){
        }
        return inputStream;
    }
}

HttpFileDownload 练习

练习

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Http {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                // HttpDown hd = new
                // HttpDown("http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip");
                HttpDown hd = new HttpDown("http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip");

                hd.SavetoDisk();
        }
}

class HttpDown {
        private String URL_PATH;

        public HttpDown(String URL_PATH) {
                this.URL_PATH = URL_PATH;
        }

        public void SavetoDisk() {
                InputStream is = null;
                FileOutputStream fo = null;
                try {
                        fo = new FileOutputStream("e:\\testFile.zip");
                        is = DownStream();
                        byte[] buffer = new byte[1024 * 1024];
                        int len = 0;
                        while ((len = is.read(buffer)) != -1) {
                                fo.write(buffer, 0, len);
                                fo.flush();
                                System.out.println(len);
                        }

                } catch (Exception e) {
                        e.printStackTrace();
                } finally {
                        try {
                                if (fo != null) {
                                        fo.close();
                                }
                                if (is != null) {
                                        is.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }

        }

        public InputStream DownStream() {
                InputStream inputStream = null;
                HttpURLConnection hul = null;

                try {
                        URL rul = new URL(URL_PATH);
                        hul = (HttpURLConnection) rul.openConnection();
                        hul.setConnectTimeout(3000);
                        hul.setReadTimeout(3000);
                        hul.setDoInput(true);
                        hul.setRequestMethod("GET");
                        if (hul.getResponseCode() == 200) {
                                inputStream = hul.getInputStream();
                        } else {
                                inputStream = null;
                        }

                } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } catch (Exception e) {
                        e.printStackTrace();
                } finally {

                }
                return inputStream;
        }

}

java HTTP 协议下的文件下载

java HTTP 协议下的文件下载

1. 建立HTTP的链接,返回输入流。
2. 读取输入流,写入输出流。


import java.net.*;
import java.io.*;
class demo{
public static void main(String[] args) {
HttpUtils hu = new HttpUtils("http://bizingeinoutetyou.com/bizinkisya/wp-content/uploads/2015/04/kiritanimirei_i04.jpg");
hu.saveImageToDisk();
}
}

class HttpUtils{
// private static String url_path = "http://bizingeinoutetyou.com/bizinkisya/wp-content/uploads/2015/04/kiritanimirei_i04.jpg";
private static String url_path ;
public HttpUtils(String url_path){
this.url_path = url_path;
}

public void saveImageToDisk(){
InputStream inputstream = getInputStream();
FileOutputStream fileoutputstream = null;
byte[] buff = new byte[1024];
int len = 0;
try{
fileoutputstream = new FileOutputStream("test.jpg");
while((len = inputstream.read(buff)) != -1){
fileoutputstream.write(buff,0,len);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(inputstream != null){
try{
inputstream.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(fileoutputstream != null){
try{
fileoutputstream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}


public static InputStream getInputStream(){
InputStream inputstream = null;
HttpURLConnection httpurlconnection = null;
try{
URL url = new URL(url_path);
httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setConnectTimeout(3000);
httpurlconnection.setDoInput(true);
httpurlconnection.setRequestMethod("GET");
int responseCode = httpurlconnection.getResponseCode();
if(responseCode == 200){
inputstream = httpurlconnection.getInputStream();
}
System.out.println(url.getFile());
System.out.println(httpurlconnection.getResponseCode());
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return inputstream;
}
}