HttpUrlConnection

webview

BufferedReader reader=new BufferedReader(new InputStream(coon.getInputStream));
reader.redaLine();
//網站解析出來獲取"類型"
webView.loadData(sb.toString,"類型",null);

imageView

URL mUrl = null;
        try {
            mUrl = new URL("網址");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection coon = null;
        try {
            coon = (HttpURLConnection) mUrl.openConnection();
            coon.setReadTimeout(5000);
            coon.setRequestMethod("GET");
            coon.setDoInput(true);
            //流
            InputStream in = coon.getInputStream();
            FileOutputStream out = null;
            File file=null;
            String fileName=String.valueOf(System.currentTimeMillis());
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File parent=Environment.getExternalStorageDirectory();
                file = new File(parent,fileName);
                out = new FileOutputStream(file);

            }
            byte[] b=new byte[1024*2];
            int len;
            if (out != null){
                while ((len=in.read())>0){
                    out.write(b,0,len);
                }
            }

            Bitmap bp= BitmapFactory.decodeFile(file.getAbsolutePath());
            handle.post(new Runnable() {
                @Override
                public void run() {
                    //TODO 主線程UI
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }

第二種

//獲取到bigmap中
URL httpUrl=new URL("**");
HttpURLConnection coon=(HttpURLConnection)httpUrl.openConnection();
coon.setReadTimeout(5000);
coon.setRequestMethod("GET");
InputStream in=coon.getInputStream();
Bitmap bp=BitmapFactory.decodeStream(in);

POST

較安全 容量大

URL mUrl = null;
        try {
            mUrl = new URL("網址");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection coon = null;
        try {
            coon = (HttpURLConnection) mUrl.openConnection();
            coon.setReadTimeout(5000);
            coon.setRequestMethod("POST");
            OutputStream out = coon.getOutputStream();\
           //根據需求
           String content = "sjx"+sjx;
           //寫
           out.write(content.getBytes());
           //讀
           BufferedReader reader=new BufferedReader(new InputStream(coon.getInputStream));
           StringBuffer sb=new StringBuffer();
           String str;
           while((str=reader.readLine()!=null){
               sb.append(str);
           }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章