Android上Java网络资源访问(二)使用HttpURLConnection多线程下载

Android-使用HttpURLConnection实现多线程下载 使用HttpURLConnection实现多线程下载这个小程序是根据《疯狂Android讲义》(第三版)第13章 Android网络应用,13.3节 使用HTTP访问网络 扩展而来。 使用多线程下载文件可以更快地完成下载任务,因为客户端启动多条线程进行下载就意味着服务器也需要为该客户端提供相应的服务。假设服务器同时最多服务100个用户,在服务器中一个线程对应一个用户,100条线程在计算机内并发 阅读详情

对网络访问不太了解的新手,可以先看一下上一篇文章对URL的简单介绍:Android上Java网络资源访问(一)使用URL类访问

1.简介 

HttpURLConnection继承于URLConnection,可以访问指定网站,HttpURLConnection通过对URLConnection的封装,使开发者在使用的过程中能够更加的方便;

URLConnection类可以使用上篇文章介绍的URL类获取,方法如下:

URLConnection connection = realUrl.openConnection();

URLConnection有多种请求方式:

摘抄如下:

Http定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE。URL全称是资源描述符,我们可以这样认为:一个URL地址,它用于描述一个网络上的资源,而HTTP中的GET,POST,PUT,DELETE就对应着对这个资源的查,改,增,删4个操作。到这里,大家应该有个大概的了解了,GET一般用于获取/查询资源信息,而POST一般用于更新资源信息。

具体参考文章:浅谈HTTP中Get与Post的区别
但是虽然URLConnection有多种交互方式,但是我们主要使用GET和POST这两种方式;

GET与POST请求。二者的区别主要在于:
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。

2. 多线程下载实例

该实例使用android应用开发,编写一个多线程下载的工具类:DownUtil,在一个界面中,一个输入框输入下载文件的url地址,一个输入框设置下载的路径,一个button响应下载,一个进度条显示下载的进度;

具体代码如下:

xml的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.anana.sockettest.DownActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="要下载的资源的url:"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="2dp"/>

    <EditText
        android:id="@+id/url"
        android:layout_width="356dp"
        android:layout_height="47dp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView"
        android:layout_marginTop="12dp"
        android:text="http://m.down.sandai.net/MobileThunder/Android_5.44.2.1966/thunder-5.44.2.5060-stable-release-OfficialSite_XunLeiProductCenter.apk"
        tools:layout_editor_absoluteX="2dp"
        tools:layout_editor_absoluteY="32dp"/>

    <EditText
        android:id="@+id/target"
        android:layout_width="222dp"
        android:layout_height="25dp"
        android:layout_alignStart="@+id/download"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="25dp"
        android:text="/mnt/sdcard/"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="117dp"
        android:layout_above="@+id/download"/>

    <Button
        android:id="@+id/download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="19dp"
        android:text="下载"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="138dp"
        android:layout_above="@+id/downbar"
        android:layout_alignParentStart="true"/>

    <ProgressBar
        android:id="@+id/downbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="270dp"
        android:layout_height="18dp"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="204dp"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/download"
        android:layout_alignStart="@+id/downbar"
        android:layout_below="@+id/url"
        android:layout_marginTop="18dp"
        android:text="目标文件:"/>
</RelativeLayout>
activity主应用代码部分:

package com.anana.sockettest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.anana.sockettest.util.DownUtil;

import java.util.Timer;
import java.util.TimerTask;

public class DownActivity extends AppCompatActivity
{

    private EditText url, target;
    private Button download;
    private ProgressBar bar;
    private Handler handler;
    private int mDownStatu;
    private DownUtil downUtil;

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

        url = (EditText) findViewById(R.id.url);
        target = (EditText) findViewById(R.id.target);
        download = (Button) findViewById(R.id.download);
        bar = (ProgressBar) findViewById(R.id.downbar);

        handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                if (msg.what == 33)
                {
                    System.out.println("mDownStatu:"+mDownStatu);
                    bar.setProgress(mDownStatu);
                }
                super.handleMessage(msg);
            }
        };

        download.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                downUtil = new DownUtil(url.getText().toString(), target.getText().toString(), 5);
                new Thread()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            downUtil.download();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }

                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask()
                        {
                            @Override
                            public void run()
                            {
                                double completeRate = downUtil.getCompleteRate();
                                mDownStatu = (int) (completeRate * 100);
                                handler.sendEmptyMessage(33);
                                if (mDownStatu >= 100)
                                {
                                    timer.cancel();
                                }

                            }
                        }, 0, 1000);
                    }
                }.start();
            }
        });

    }
}

DownUtil类的编写,核心部分:

package com.anana.sockettest.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by wolfboyjiang on 2017/8/31.
 */

public class DownUtil
{
    private String path;
    private String targetFile;
    private int threadnum;
    private int fileSize;
    private DownThread[] threads;

    public DownUtil(String path, String targetFile, int threadnum)
    {
        this.path = path;
        this.targetFile = targetFile;
        this.threadnum = threadnum;
        threads = new DownThread[threadnum];
    }

    public void download() throws Exception
    {
        System.out.println("download start ,url:"+path);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        //设置通用的请求属性
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Accept-Language", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
//        conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
// 5.1; SV1)");
        fileSize = conn.getContentLength();
        conn.disconnect();
        int currentPartSize = fileSize / threadnum + 1;
        System.out.println("currentPartSize:"+currentPartSize+",currentPartSize:"+currentPartSize);
        RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
        file.setLength(fileSize);
        file.close();
        for (int i = 0; i < threadnum; i++)
        {
            int startPos = i * currentPartSize;
            RandomAccessFile currentPart = new RandomAccessFile(targetFile, "rw");
            currentPart.seek(startPos);
            threads[i] = new DownThread(startPos, currentPartSize, currentPart);
            threads[i].start();

        }
    }

    public double getCompleteRate()
    {
        int sumSize = 0;
        for (int i = 0; i < threadnum; i++)
        {
            sumSize += threads[i].length;
        }
        System.out.println("fileSize:"+fileSize+",sumSize:"+sumSize);
        return sumSize * 1.0 / fileSize;
    }

    private class DownThread extends Thread
    {
        private int startPos = 0;
        private int currentPartSize;
        private RandomAccessFile currentpart;
        public int length = 0;

        public DownThread(int startPos, int currentPartSize, RandomAccessFile currentpart)
        {
            this.startPos = startPos;
            this.currentPartSize = currentPartSize;
            this.currentpart = currentpart;
        }

        @Override
        public void run()
        {
            try
            {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                //设置通用的请求属性
                conn.setRequestProperty("Accept", "*/*");
                conn.setRequestProperty("Accept-Language", "UTF-8");
                conn.setRequestProperty("Connection", "Keep-Alive");

                InputStream in = conn.getInputStream();
                skipFully(in,this.startPos);

                byte[] buffer = new byte[1024];
                int hasRead = 0;
                while (length < currentPartSize && (hasRead = in.read(buffer)) > 0)
                {
                    currentpart.write(buffer,0,hasRead);
                    length += hasRead;
                }
                currentpart.close();
                in.close();

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


    }

    public static void skipFully(InputStream in, long bytes) throws IOException
    {
        long remainning = bytes;
        long len = 0;
        while (remainning > 0)
        {
            len = in.skip(remainning);
            remainning -= len;
        }
    }
}




Android网络资源获取实战演示 超文本传输协议(HTTP)是一种用于分布式、协作式和超媒体信息系统的应用层协议。它是互联网上应用最广泛的协议之一,用于从服务器传输超文本到本地浏览器。HTTP协议是一个基于请求/响应的模型,工作在TCP/IP协议之上。它定义了客户端和服务器之间交互的消息格式。基本的HTTP操作包含GET和POST两种请求方法。GET:从指定的资源请求数据。POST:向指定的资源提交要被处理的数据。 阅读详情

相关推荐

网络请求----HttpURLConnection的get,post和图片加载

HttpURLConnection的get,post和图片加载

Android HTTP客户端:GET,POST,下载,上传,分段请求

通常,Android应用程序必须与远程服务器交换信息。 最简单的方法是使用HTTP协议作为基础来传输信息。 HTTP协议在许多情况下非常有用,例如从远程服务器下载图像或将一些二进制数据上传到服务器。 Android应用执行GET或POST请求以发送数据。 在本文中,我们要分析如何使用HttpURLConnection与远程服务器进行通信。 我们将涵盖三个主要主题: GET和POST请求...

563

Revit获取族预览图

最近做到和族库相关的功能需要获取到族文件的预览图,在RevitAPI中提供了ElementType.GetPreviewImage方法,但是前提就是你是在Revit里面操作的,并且已经拿到了Symbol对象实例,才可以调用此方法。然后在网上找了另外一种方式,通过读取Revit文件,在REVITPREVIEW4.0字段截取文件信息,将其转换为图片格式。 一、使用RevitAPI中ElementType.GetPreviewImage方法 [Autodesk.Revit.Attributes.Transac.

weixin_44631419的博客 1753

Android HTTP访问的两种方式(HttpClient和HttpURLConnection)

Android HTTP访问的两种方式(HttpClient和HttpURLConnection)

Crazy程序猿 5405

数字后端实战指南 | Innovus Function ECO全流程解析(从LAB到Tapeout)

本文深入解析了在Cadence Innovus工具中进行Function ECO的全流程实战指南。从LAB环境搭建到Tapeout前的签核验证,详细拆解了Pre-mask与Post-mask ECO的核心步骤、关键命令(如ecoDesign)以及常见避坑方案。重点阐述了如何应对时序、DRC等挑战,并强调了备用单元管理与严格验证的重要性,是数字后端工程师提升综合能力的必备参考。

weixin_28452161的博客 639

发那科机器人通信库使用指南与踩坑记录

GitHubNuGet(如本文基于该库,在 C# / .NET 下通过 TCP 与 FANUC 机器人控制器通信,实现读当前位姿、PR 寄存器、以及 DI/DO/GI/GO 等 IO 的读写。GitHubNuGet(如本文基于该库,在 C# / .NET 下通过 TCP 与 FANUC 机器人控制器通信,实现读当前位姿、PR 寄存器、以及 DI/DO/GI/GO 等 IO 的读写。

songhuangong123的博客 323

Android httpUrlConnection的基本使用

今天,简单讲讲Android HttpUrlConnection的使用。 我在项目里是使用OK HTTP的,但是最近发现使用OK HTTP好多不知道的问题,感觉自己对基本的网络请求不是很好的掌握,所以学习一下基本的网络请求类:HttpUrlConnection。 一,HttpURLconnection的介绍 在Android开发中网络请求是最常用的操作之一, Android SDK中对H...

谢岩的博客 1万+

【麒麟系统】Rsync文件复制与同步工具

本文摘要: Rsync是一款Linux/Unix系统标配的高效文件同步工具,支持增量传输、SSH加密、断点续传等核心功能,相比SCP具有显著优势。文章详细解析了Rsync的五种标准语法格式和常用参数组合,重点介绍了本地同步、远程SSH同步(推送/拉取)的实操方法,并提供了密钥免密登录配置方案。针对企业运维场景,还讲解了文件过滤、镜像同步(--delete)、迁移同步(--remove-source-files)、空运行预校验(--dry-run)等高级功能,以及带宽限速等优化技巧,帮助用户安全高效地完成各类

信创运维工程师 · 银河麒麟 & 容器实战 | 金融生产环境迁移·等保加固 | 142篇原创·17万+阅读 998

Android中Http请求

Android中的网络请求可以分为两种,HttpUrlConnection还有HttpClient,虽然Android中的网络请求框架很多,或许看起来让人觉得眼花缭乱,比如,vollery,Afinal等等。 但是万变不离其宗,这些框架都是根据这两个网络请求多次封装而成的。下面就主要介绍一下HttpUrlConnection和HttpClient。 Http(Hypertext Tra

zhuxiaoxuand的博客 794

【Python爬虫(90)】以Python爬虫为眼,洞察金融科技监管风云

本文聚焦爬虫技术在金融科技监管中的应用。开篇阐述金融科技发展带来监管挑战,引出爬虫技术的重要性。接着介绍金融科技监管政策与合规要求,包括政策法规体系、合规细则及政策变化应对。随后探讨爬虫技术选型、数据监测策略、风险指标抓取及案例实操。还阐述基于爬虫数据构建风险预警与防控机制,含模型构建、阈值设定等。最后总结爬虫技术应用成果,展望其与人工智能融合、适应新监管需求及重视数据安全的未来发展趋势。

邓邓子的博客 1063

SST专题(2-2)MMC-SST 输入级的工作原理及数学模型

本文研究了MMC-SST和iMMC-SST的电路结构及工作原理。系统由前级MMC电路和后级DC/DC电路组成,MMC负责电能转换和能量存储,DC/DC电路进行电压电流调节。重点分析了半桥型子模块(SM)的开关组态和工作原理,建立了平均值模型,推导了上下桥臂电压方程和环流特性。研究表明,通过合理控制子模块充放电模态可维持端口电压平衡,上下桥臂电压调控可影响网侧功率吸收,而环流特性对中压直流侧电压具有重要影响。

嵌入式老牛的博客 772

Android使用HttpURLConnection下载图片

讲到http就必需要了解URI和URL URI (uniform resource identifier)统一资源标志符; URL(uniform resource location )统一资源定位符(或统一资源定位器); 可以理解成URL是URI的子集,URI是一抽象的标识符,URL可以理解成具体的标识符;只要是网络上的资源就能找到唯一的URL。

DMT专栏 6553

Android网络编程之使用HTTP访问网络资源

前面介绍了 URLConnection己经可以非常方便地与指定站点交换信息,URLConnection还有一个子类:HttpURLConnection,HttpURLConnection 在 LIRLConnection的基础上做了进一步改进,增加了一些用于操作http资源的便捷方法

fengyuzhengfan的专栏 7491

企业级 Token 中转架构设计:高并发、多模型、费用监控一次搞定

摘要:本文针对企业级AI开发中的多模型接口混乱、高并发稳定性差及Token费用失控等痛点,提出一套2026年企业级Token中转架构解决方案。该方案采用五层分层设计(接入层、网关层、调度层、服务层、存储层),实现多模型统一接口、智能路由、高并发限流容错及精细化成本监控。核心功能包括:异构模型标准化接入、动态路由策略(场景/成本/负载/容灾)、多级限流熔断机制、全链路Token计费与安全防封体系(指纹清洗、IP池隔离)。通过分层解耦与模块化设计,企业可降低50%成本、提升99%稳定性,并避免封号风险。文章还提

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 145

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

安卓使用http下载文件

在安卓中,可以直接用java的java.net.URL包访问网络下载数据。不同的是,安卓程序需要权限,需要在AndroidManifest.xml文件中声明权限 不过有个需要注意的是,我使用的是最新的adt安卓开发集成eclipse的安装包,在使用网络服务的时候,处理网络请求的代码,不能在主线程中进行,不然安卓会提示错误。 但是,有些组件设置值,他必须是在主

sujudz的专栏 3万+

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Android移动开发-使用HttpURLConnection实现多线程的下载

实例Demo程序来示范使用HttpURLConnection实现多线程下载。 使用多线程下载文件可以更快完成文件的下载,因为客户端启动多条线程进行下载就意味着服务器也需要为该客户端提供响应的服务。假设服务器同时最多服务100个用户,在服务器中一条线程对应一个用户,100条线程在计算机内并发执行,也就是有CPU划分时间片轮流执行,如果A应用使用了99条线程下载文件,那么相当于占用了99个用户的资源,自然就拥有了较快的下

_彼岸雨敲窗_的博客 1480

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Android网络编程之使用HTTP訪问网络资源

使用HTTP訪问网络资源        前面介绍了 URLConnection己经能够很方便地与指定网站交换信息,URLConnection另一个子类:HttpURLConnection,HttpURLConnection 在 LIRLConnection的基础上做了进一步改进,添加了一些用于操作http资源的便捷方法。 1.使用HttpURLConnection       Htt...

weixin_33795806的博客 122

android 文件夹 下载,Android 文件下载(1)

1.项目用到的图片上传的关键方法:哈喽,我又来了,现在是2021年1月19号上午10点35分,给大家分享些文件上传的方法,有需要的继续往下看呦!1.普通单线程下载文件:直接使用URLConnection.openStream()打开网络输入流,然后将流写入到文件中!核心方法:public static void downLoad(String path,Context context)throws...

weixin_34404528的博客 2898

Android的网络应用-使用HttpURLConnection

Android的网络应用-使用HttpURLConnection 实例:多线程下载 实现多线程的步骤: 1.创建URL对象。 2.获取指定URL对象所指向资源的大小。 3.在本地磁盘上创建一个与网络资源相同大小的空文件。 4.计算每条线程应该下载网络资源的哪个部分(从哪个字节开始,到哪个字节结束) 5.依次创建,启动多线程来下载网络资源的指定部分   创建项目:MultiThre

巫山老妖 3416

Android_访问网络一(使用HttpURLConnection访问)

Android 为我们提供了两种访问网络的方式: 一、           HttpURLConnection 二、           HttpClient 当然,除了以上两种,还有其它一些封装好的框架,我们可以很方便的拿来使用,比如android-async-http,以及Google提供的Volley   现在,先来看看如何使用HttpURLConnection对网络资源进行访问

blank 的专栏 879

Java中HttpURLConnection与HttpClient

Java中HttpURLConnection与HttpClient

Rebirth_Love的博客 703

php 安卓下载文件,Android 文件下载(1)

本节引言:又是一个深坑,初学者慎入...本节将从普通的单线程下载 -> 普通多线程下载 ->-> 以及一个很实用的例子:利用Android那只DownloadManager更新apk并覆盖安装的实现代码!好的,这样看上去,本节还是蛮有趣的,开始本节内容!PS:我们把整个完整的多线程断点续传放到下一节中!1.普通单线程下载文件:直接使用URLConnection.openStrea...

weixin_29485887的博客 501
上一篇: Android上Java网络资源访问(一)使用URL类访问
下一篇: Android webview控件(一) 使用webview开发浏览器实例
Anana_JP
博客等级 码龄17年 11粉丝 18原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值