android学习——网络访问HttpURLConnection

Android网络(二)原生的HTTP请求工具--HttpURLConnection的用法 作为 Android 系统提供的原生 HTTP 请求工具,尽管功能相对简单,但它仍然具备处理基本网络请求的能力。其轻量级和系统内置的特性,使得在一些简单或对性能要求较高的场景中仍然被广泛使用。然而,随着现代应用对网络请求的复杂性和高效性的要求越来越高,的局限性也逐渐显现。比如,处理复杂的网络请求、增强的连接池管理、更好的性能优化等需求,往往需要更强大的工具来应对,OkHttp作为一个开源的 HTTP 客户端,提供了许多所不具备的高级特性。 阅读详情

我们知道大多数的 Android 应用程序都是通过和服务器进行交互来获取数据的。如果使用 HTTP 协议来发送和接收网络数据,就免不了使用 HttpURLConnection 和 HttpClient,而 Android 中主要提供了上述两种方式来进行 HTTP 操作。并且这两种方式都支持 HTTPS 协议、以流的形式进行上传和下载、配置超时时间、IPv6、以及连接池等功能。

但是 Googl e发布 6.0 版本的时候声明原生剔除 HttpClient,详情可以看http://blog.csdn.net/guolin_blog/article/details/12452307。

接着我们来看一下如何使用 HttpURLConnection 的GET和POST来处理简单的用户登录请求。



<span style="white-space:pre">	</span>// 点击按钮 进行get方式提交数据
<span style="white-space:pre">	</span>public void click1(View v) {
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>new Thread(){public void run() {
<span style="white-space:pre">			</span>


<span style="white-space:pre">			</span>try {
<span style="white-space:pre">			</span>//获取用户名和密码 
<span style="white-space:pre">			</span>String name = et_username.getText().toString().trim();
<span style="white-space:pre">			</span>String pwd = et_password.getText().toString().trim();
<span style="white-space:pre">			</span>//定义get方式要提交的路径    小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码 
<span style="white-space:pre">			</span>String path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
<span style="white-space:pre">		</span>
<span style="white-space:pre">				</span>//(1) 创建一个url对象 参数就是网址 
<span style="white-space:pre">				</span>URL url = new URL(path);
<span style="white-space:pre">				</span>//(2)获取HttpURLConnection 链接对象
<span style="white-space:pre">				</span>HttpURLConnection conn = (HttpURLConnection) url.openConnection();
<span style="white-space:pre">				</span>//(3)设置参数  发送get请求
<span style="white-space:pre">				</span>conn.setRequestMethod("GET"); //默认请求 就是get  要大写
<span style="white-space:pre">				</span>//(4)设置链接网络的超时时间 
<span style="white-space:pre">				</span>conn.setConnectTimeout(5000);
<span style="white-space:pre">				</span>//(5)获取服务器返回的状态码 
<span style="white-space:pre">				</span>int code = conn.getResponseCode(); //200  代表获取服务器资源全部成功  206请求部分资源    
<span style="white-space:pre">				</span>if (code == 200) {
<span style="white-space:pre">					</span>//(6)获取服务器返回的数据  以流的形式返回   
<span style="white-space:pre">					</span>InputStream inputStream = conn.getInputStream();


<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(6.1)把inputstream 转换成 string 
<span style="white-space:pre">					</span>String content = readStream(inputStream);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(7)把服务器返回的数据展示到Toast上  不能在子线程展示toast
<span style="white-space:pre">					</span>showToast(content);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">				</span>}


<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>};}.start();
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>// [1]点击按钮 进行post方式提交数据
<span style="white-space:pre">	</span>public void click2(View v) {


<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>new Thread(){public void run() {
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">			</span>//[2]获取用户名和密码 
<span style="white-space:pre">			</span>String name = et_username.getText().toString().trim();
<span style="white-space:pre">			</span>String pwd = et_password.getText().toString().trim();
<span style="white-space:pre">			</span>//[2.1]定义get方式要提交的路径 
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>String data = "username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd,"utf-8")+""; //请求体的内容
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>// 一 ☆☆☆☆☆☆☆和get方式提交数据 区别 路径不同
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>String path = "http://192.168.11.73:8080/login/LoginServlet";
<span style="white-space:pre">		</span>
<span style="white-space:pre">				</span>//(1) 创建一个url对象 参数就是网址 
<span style="white-space:pre">				</span>URL url = new URL(path);
<span style="white-space:pre">				</span>//(2)获取HttpURLConnection 链接对象
<span style="white-space:pre">				</span>HttpURLConnection conn = (HttpURLConnection) url.openConnection();
<span style="white-space:pre">				</span>//(3)设置参数  发送get请求
<span style="white-space:pre">				</span>
<span style="white-space:pre">		</span>    //二 ☆☆☆☆☆☆☆和get方式提交数据 区别  设置请求方式是post
<span style="white-space:pre">				</span>conn.setRequestMethod("POST"); //默认请求 就是get  要大写
<span style="white-space:pre">				</span>//(4)设置链接网络的超时时间 
<span style="white-space:pre">				</span>conn.setConnectTimeout(5000);
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>
<span style="white-space:pre">			</span>//三 <span style="white-space:pre">	</span> ☆☆☆☆☆☆☆和get方式提交数据 区别 要多设置2个请求头信息 
<span style="white-space:pre">				</span>//设置头信息
<span style="white-space:pre">				</span>conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
<span style="white-space:pre">				</span>conn.setRequestProperty("Content-Length", data.length()+"");
<span style="white-space:pre">				</span>
<span style="white-space:pre">			</span>
<span style="white-space:pre">				</span>conn.setDoOutput(true);// 设置一个标记 允许输出 
<span style="white-space:pre">				</span>//四 ☆☆☆☆☆☆☆ 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容 
<span style="white-space:pre">				</span>OutputStream out = conn.getOutputStream();
<span style="white-space:pre">				</span>out.write(data.getBytes());
<span style="white-space:pre">				</span>out.flush();  
<span style="white-space:pre">				</span>out.close(); 
<span style="white-space:pre">				
</span>
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>//(5)获取服务器返回的状态码 
<span style="white-space:pre">				</span>int code = conn.getResponseCode(); //200  代表获取服务器资源全部成功  206请求部分资源    
<span style="white-space:pre">				</span>if (code == 200) {
<span style="white-space:pre">					</span>//(6)获取服务器返回的数据  以流的形式返回   
<span style="white-space:pre">					</span>InputStream inputStream = conn.getInputStream();
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(6.1)把inputstream 转换成 string 
<span style="white-space:pre">					</span>String content = readStream(inputStream);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>//(7)把服务器返回的数据展示到Toast上  不能在子线程展示toast
<span style="white-space:pre">					</span>showToast(content);
<span style="white-space:pre">					</span>
<span style="white-space:pre">					</span>
<span style="white-space:pre">				</span>}


<span style="white-space:pre">			</span>} catch (Exception e) {
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>};}.start();
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span><pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 22.4px;">//封装把一个inputStream 转换成一个String的方法
 private static String readStream(InputStream is)
             throws IOException {
         ByteArrayOutputStream os = new ByteArrayOutputStream();
         // 模板代码 必须熟练
         byte[] buffer = new byte[1024];
         int len = -1;
         while ((len = is.read(buffer)) != -1) {
             os.write(buffer, 0, len);
         }
         is.close();
         String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
         os.close();
         return state;
     }
//封装toast方法  该toast方法执行在主线程 
public void showToast(final String content){
runOnUiThread(new Runnable() {

@Override
public void run() {
//该方法一定是执行主线程 
Toast.makeText(getApplicationContext(), content, 1).show();


}
});

}

Android使用HttpURLConnection访问网络 Android上可以通过HttpURLConnection发送HTTP请求来访问网络,具体步骤如下: 1.获取HttpURLConncetion实例 通过调用url实例的openConnection()方法即可,代码如下: URL url = new URL("htp://www.baidu.com"); HttpURLConnection connection = (HttpURLCon... 阅读详情

相关推荐

Android 三种常用网络访问方式HttpURLConnection、Volley和okhttp3

三种方法的差异 HttpURLConnection、和okhttp3是Android最常用的三种网络方式,其主要差别是: 1、HttpURLConnection为同步的方式,Volley只支持异步的方法,而okhttp3同时支持同步和异步的方法。 2、HttpURLConnection与Volley不支持WebSocket,而okhttp3是支持的。 同步的网络访问方式不能在主线程中使用,必须通过...

dingpwen的博客 1424

Android HttpURLConnection(Get,Post方式)进行网络通信 获取数据和网络图片

前言          欢迎大家我分享和推荐好用的代码段~~ 声明          欢迎转载,但请保留文章原始出处:          CSDN:http://www.csdn.net          雨季o莫忧离:http://blog.csdn.net/luckkof 正文

奥特曼 1535

使用HttpURLConnection访问网络--android 第一行代码

在以前,Android发送HTTP请求一般有两种方式,HttpURLConnection和HttpClient。但是由于后者使用起来过于麻烦(API数量过多,扩展困难等),然后在Android6.0系统中,HttpClient功能完全被移除。 HttpURLConnection使用方法比较简单,步骤如下: 如果使用HttpURLConnection当然少不了先获取他的实例了。 实例获取成功之...

z1web的博客 1383

Android使用Http协议访问网络——HttpConnection

套路篇 使用HttpConnection访问网络一般有如下的套路: 1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection()方法。 1 HttpURLConnection connection=null; 2 URL url=new URL("http://www.baidu.com"); 3 connect...

weixin_30666401的博客 161

Android Studio的网络连接HttpURLConnection.

上篇的博客里面我说了,现在Android6.0已经将Httpclient废弃不用了,在AndroidStudio上使用的话会出现报错的情况。虽然现在在SDK中还是能找到这个类,同时使用,但是总是不方便,我们总要更新网络请求的。下面是我写的简单的HttpURLConnection请求代码。 HttpRequestUtil代码: package com.yami.baichi.net; im

u013062469的专栏 9344

vscode中创建vue快捷键

1.安装Vetur插件(扩展里面直接搜) 2.vscode 界面里面左上角选则 文件=> 首选项=> 用户代码片段=>新建全局代码片段=>在输入框中新建名称为vue.json 3.删除里面的注释,当然你也可以留着,把下面的代码粘贴进去! { // Place your 全局 snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and // descri

Leon_940002463的博客 3218

Android 之 HTTP请求方式:HttpURLConnection

答:一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。虽然HttpURLConnection的API提供的比较简单,但是同时这也使得我们可以更加容易地去使 用和扩展它。继承至URLConnection,抽象类,无法直接实例化对象。通过调用() 方法获得对象实例,默认是带gzip压缩的;

leyang0910的博客 1774

别再到处找模板了!手把手教你用Vue3+Element Plus搭建一个‘能跑起来’的管理后台原型

本文详细介绍了如何利用Vue3和Element Plus在72小时内快速搭建一个功能完整的管理后台原型。从环境准备到项目获取、依赖安装、原型定制、数据模拟以及构建优化,手把手教你打造一个可直接演示的后台系统,特别适合创业者快速验证产品逻辑。

weixin_26854555的博客 190

Android学习之使用HTTP协议访问网络之HttpURLConnection

#转自第一行代码—郭霖 首先new出一个URL对象,传入目标对象的网络地址,再new一个HttpURLConnection的实例,然后调用URL的openConnection()方法即可。如下代码所示: URL url = new URL("https://www.baidu.com/"); HttpURLConnection connection = null; connection = (HttpURLConnection) url.openConnection(); 在得到HttpURLCon

weixin_37879993的博客 233

从零搭建基于OpenSpec的现代化UI自动化测试框架实战指南

UI自动化测试是软件质量保障的关键环节,其核心在于通过脚本模拟用户操作,对Web应用界面进行功能验证。其原理在于利用浏览器驱动工具(如Selenium、Playwright)提供的API,实现对页面元素的定位、交互与断言。一个设计良好的自动化框架能显著提升测试脚本的可维护性、可读性和执行稳定性,从而在持续集成、回归测试等场景中发挥巨大价值。本文聚焦于如何构建一个现代化的UI测试框架,通过整合OpenSpec架构规范、Pytest测试引擎与Playwright浏览器自动化工具,形成清晰的页面对象模型(POM)

weixin_28836989的博客 297

逆向淘宝x-mini-wua:从加密算法到设备指纹的生成逻辑

本文深入剖析了淘宝风控核心参数x-mini-wua的生成逻辑与加密算法。通过逆向分析,揭示了其作为设备“身份证”的作用,详细拆解了从硬件信息采集、SG_INNER_DATA文件解密、关键参数提取到最终长wua合成的完整技术链条,并探讨了模拟生成与绕过风控的实战思路及注意事项。

year5的博客 1118

Android 学习笔记——http 访问网络,get、post请求(HttpURLConnection版)

在Android开发中,经常需要通过网络与服务器进行数据交互。HTTP是一种常用的协议,它提供了一种简单的方式来进行网络通信。本篇学习笔记将介绍如何在Android应用中使用HTTP进行网络请求,包括GET和POST请求的实现。

mobi的博客 2563

在 ABAP 中把变量一次写对:深入理解 FINAL 内联声明与不可变变量

摘要:ABAP中的FINAL声明操作符用于定义不可变变量,强调"当前上下文中的唯一写位置",能有效防止变量被意外修改,提升代码健壮性和可读性。官方建议优先在单次赋值的场景使用FINAL替代DATA。其核心规则包括:1)写位置唯一但可多次执行(如循环内);2)不创建块级作用域;3)对引用变量仅约束引用本身而非对象内容。典型适用场景包括:结果值只读、输入快照保存和中间结果保护。例外情况如游标变量不适用,因需多次写操作。正确使用FINAL可显著降低代码维护风险。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1058

深入学习Android有关网络连接的内容

基于实际项目中碰到的些许问题,开始重新深入学习Android网络连接有关知识。 Android的4.1.2版本的AndroidHttpClient模块setSoTimeout之后实际超时时间和设置的时间不一致现象 不知何种原因,高版本平台使用AndroidHttpClient(setSoTimeout设置的超时时间为60秒),实际反应出的超时时间不一致,需要4分钟才超时。 设备1:U...

weixin_34343000的博客 160

2025年新发表的语音大模型全双工模型/框架/技术

参考该论文,给出2025年新发表的全双工模型或框架或技术下面这份清单专挑、且与“全双工语音对话/同步对话(边听边说、可打断、回馈/相槌、重叠语音)”直接相关的。我也结合你提到的的四大维度(暂停处理、相槌、顺滑换手、打断管理)来点出它们各自的贡献点,便于后续评测与对比。

u013250861的博客 649

OpenMVS :用 colmap制作自己的数据集 重建(用colmap计算位姿,将位姿转为MVS需要的格式)

数据集制作主要是在windows进行,比较方便。

程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。 3336

【学习笔记-Android】(十三) 网络篇(一)——HttpURLConnection

网络篇笔记链接: 一、HttpURLConnection 二、Volley框架 + 使用Gson解析json数据 三、OkHttp3框架 + 使用Gson解析json数据 四、WebView组件 五、Android 9.0以上不能访问网络问题解决方法 =============================================================== 使用HttpURLConnection 本文目录: 1、GET请求 2、POST请求 提示:Android 9.0 版本之后的网络访

AlanLee97的博客 274

【碳排放数据集】全球近实时网格化二氧化碳排放数据集GRACED

【碳排放数据集】全球近实时网格化二氧化碳排放数据集GRACED

WW、forever的博客 158

Android 通过HttpURLConnection访问Http协议网络

本文目录第一步:添加网络访问权限第二步:使用HttpURLConnection访问网络代码示例 Android原生目前支持两种方式访问http协议的网络,第一种是HttpURLConnection,另外一种是oKHttp,下面来介绍一下用HttpURLConnection来访问访问http协议的方法 第一步:添加网络访问权限 在AndroidManifest.xml文件中添加如下权限 <u...

lucashu的博客 3723

深度学习工具包 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")

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

android网络访问之HttpURLConnection vs OkHttp

首先HttpURLConnection是原生的android网络访问的API,而OkHttp则是第三方的包; 其次,测试发现 1、HttpURLConnection的使用: package zjava.data.request; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import

壁立千仞无欲则刚的博客 3367

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Android访问网络,使用HttpURLConnection还是HttpClient?

大多数的Android应用程序都会使用HTTP协议来发送和接收网络数据,而Android中主要提供了两种方式来进行HTTP操作,HttpURLConnection和HTTPClient。这两种方式都支持HTTPS协议、以流的形式进行上传和下载、配置超时时间、IPv6、以及连接池等功能。 DefaultHttpClient和它的兄弟AndroidHttpClient都是HttpClient具体的实现类,它们都拥有众多的API,而且实现比较稳定,bug数量也很少。 但同时也由于HttpClient的API数量过

郭霖的专栏 11万+

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

android访问网络的方法,Android 用HttpURLConnection访问网络的方法

一、 HttpURLConnection以GET方式访问网络:HttpURLConnection connection = null;try {URL url = new URL("https://www.xxx.com/");connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET...

weixin_39619270的博客 591

Android学习:访问网络

1、Get请求和Post请求简介 当客户端与服务器建立了网络链接之后,就可以发送Http请求了。Http请求通常分为Get请求和Post请求两种,下面分别介绍: 1.Get请求 Get:通过请求URI得到资源,一般用于获取/查询资源信息。 Get请求比较简单,只需要在指定的链接地址中,将需要传递的参数通过“?参数名=参数值”的格式进行传递,如果传递的参数不止一个,则需要使用英文半角的“,“将各个参数进行分隔。例如,要传递用户编号和用户名这两个参数,相应的参数传递格式为”http:...

weixin_52021660的博客 1672

android链接网络的方法,Android 用HttpURLConnection访问网络的方法

一、 HttpURLConnection以GET方式访问网络:HttpURLConnection connection = null;try {URL url = new URL("https://www.xxx.com/");connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET...

weixin_42361112的博客 555

HttpClient、HttpURLConnection协议访问网络

HttpClient、HttpURLConnection协议访问网络 一:HttpClient简介 HttpClient是什么? HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。 尽管java.net软件包提供了用于通过HTTP访问资源的基本功能,但它并未提供许多应用程序所需的全部灵活性或功能。HttpClient试图通过提供高效,最新且功能丰富的程序包来实现此空白,以实现最新HTTP标准和建议的客

GuanGuBin的博客 624
上一篇: android学习——Handler引起的内存泄露及解决方法
下一篇: android学习——使用开源程序AsyncHttpClient访问网络
linlif
博客等级 码龄15年 3粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值