【HttpClient4.5中文教程】【第一章 :基础】1.3 HttpClient执行上下文

吃透HTTP一:Http请求HttpUrlConnection,HttpClient、OKHttp详细介绍 一,HTTP概述 HTTP协议是无状态的协议,即每一次请求都是互相独立的。因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接。 HTTP协议是全双工的协议,所以建立连接与断开连接是要经过三次握手与四次挥手的。显然在这种设计中,每次发送Http请求都会消耗很多的额外资源,即连接的建立与销毁。 于是,HTTP协议的也进行了发展,通过持久连接的方法来进行socket连接复用。 HTTP/1.0+的Keep-Alive 使用HTTP/1.0的客户端在首部中加上"C 阅读详情

1.3.Http执行上下文(context)


最初,HTTP是被设计成无状态的,面向请求-响应的协议。然而,现实世界中的应用程序经常需要通过一些逻辑相关的请求-响应交换来保持状态信息。 为了使应用程序能够维持一个过程状态, HttpClient允许HTTP请求在一个特定的执行上下文中来执行–称为HTTP上下文。如果相同的上下文在连续请求之间重用,那么多种逻辑相关的请求可以参与到一个逻辑会话中。HTTP上下文功能和java.util.Map<String,Object>很相似。 它仅仅是任意命名参数值的集合。应用程序可以在请求之前填充上下文属性,也可以在执行完成之后来检查上下文属性。


HttpContext能够包含任意的对象,因此在两个不同的线程中共享上下文是不安全的,建议每个线程都一个它自己执行的上下文。


在HTTP请求执行的这一过程中, HttpClient添加了下列属性到执行上下文中:
  • `HttpConnection实例代表连接到目标服务器的当前连接。
  • `HttpHost实例代表连接到目标服务器的当前连接。
  • `HttpRoute实例代表了完整的连接路由。
  • `HttpRequest实例代表了当前的HTTP请求。最终的HttpRequest对象在执行上下文中总是准确代表了状态信息,因为它已经发送给了服务器。每个默认的HTTP/1.0 和 HTTP/1.1使用相对的请求URI,可是,请求以non-tunneling模式通过代理发送时,URI会是绝对的。
  • `HttpResponse实例代表当前的HTTP响应。
  • `java.lang.Boolean对象是一个标识,它标志着当前请求是否完整地传输给连接目标。
  • `RequestConfig代表当前请求配置。
  • `java.util.List<URI>对象代表一个含有执行请求过程中所有的重定向地址。
 
你可以使用HttpClientContext适配器类来简化上下文状态的活动。
  1. HttpContext context = <…>  
  2. HttpClientContext clientContext = HttpClientContext.adapt(context);  
  3. HttpHost target = clientContext.getTargetHost();  
  4. HttpRequest request = clientContext.getRequest();  
  5. HttpResponse response = clientContext.getResponse();  
  6. RequestConfig config = clientContext.getRequestConfig();  
HttpContext context = <...>
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpHost target = clientContext.getTargetHost();
HttpRequest request = clientContext.getRequest();
HttpResponse response = clientContext.getResponse();
RequestConfig config = clientContext.getRequestConfig();

  
代表一个逻辑相关的会话中的多个请求序列应该被同一个HttpContext实例执行,以确保请求之间会话上下文和状态信息的自动传输。
 
下面的例子中:请求配置在最初被初始化,它将在执行上下文中一直保持。共享与同一个会话中所有连续的请求。
  1.  CloseableHttpClient httpclient = HttpClients.createDefault();  
  2. RequestConfig requestConfig = RequestConfig.custom()  
  3.     .setSocketTimeout(1000)  
  4.     .setConnectTimeout(1000)  
  5.     .build();  
  6. HttpGet httpget1 = new HttpGet(“http://localhost/1”);  
  7. httpget1.setConfig(requestConfig);  
  8. CloseableHttpResponse response1 = httpclient.execute(httpget1, context);  
  9. try {  
  10.     HttpEntity entity1 = response1.getEntity();  
  11. } finally {  
  12.     response1.close();  
  13. }  
  14. HttpGet httpget2 = new HttpGet(“http://localhost/2”);  
  15. CloseableHttpResponse response2 = httpclient.execute(httpget2, context);  
  16. try {  
  17.     HttpEntity entity2 = response2.getEntity();  
  18. } finally {  
  19.     response2.close();  
  20. }   
 CloseableHttpClient httpclient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
    .setSocketTimeout(1000)
    .setConnectTimeout(1000)
    .build();
HttpGet httpget1 = new HttpGet("http://localhost/1");
httpget1.setConfig(requestConfig);
CloseableHttpResponse response1 = httpclient.execute(httpget1, context);
try {
    HttpEntity entity1 = response1.getEntity();
} finally {
    response1.close();
}
HttpGet httpget2 = new HttpGet("http://localhost/2");
CloseableHttpResponse response2 = httpclient.execute(httpget2, context);
try {
    HttpEntity entity2 = response2.getEntity();
} finally {
    response2.close();
} 

=========================总结======================

  
  1. import java.util.List;  
  2.   
  3. import org.apache.http.client.CookieStore;  
  4. import org.apache.http.client.methods.CloseableHttpResponse;  
  5. import org.apache.http.client.methods.HttpGet;  
  6. import org.apache.http.client.protocol.HttpClientContext;  
  7. import org.apache.http.cookie.Cookie;  
  8. import org.apache.http.impl.client.BasicCookieStore;  
  9. import org.apache.http.impl.client.CloseableHttpClient;  
  10. import org.apache.http.impl.client.HttpClients;  
  11. import org.apache.http.util.EntityUtils;  
  12.   
  13. /** 
  14.  * This example demonstrates the use of a local HTTP context populated with 
  15.  * custom attributes. 
  16.  */  
  17. public class ClientCustomContext {  
  18.   
  19.     public final static void main(String[] args) throws Exception {  
  20.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  21.         try {  
  22.             // Create a local instance of cookie store  
  23.             CookieStore cookieStore = new BasicCookieStore();  
  24.   
  25.             // Create local HTTP context  
  26.             HttpClientContext localContext = HttpClientContext.create();  
  27.             // Bind custom cookie store to the local context  
  28.             localContext.setCookieStore(cookieStore);  
  29.   
  30.             HttpGet httpget = new HttpGet(“http://localhost/”);  
  31.             System.out.println(”Executing request ” + httpget.getRequestLine());  
  32.   
  33.             // Pass local context as a parameter  
  34.             CloseableHttpResponse response = httpclient.execute(httpget, localContext);  
  35.             try {  
  36.                 System.out.println(”—————————————-“);  
  37.                 System.out.println(response.getStatusLine());  
  38.                 List<Cookie> cookies = cookieStore.getCookies();  
  39.                 for (int i = 0; i < cookies.size(); i++) {  
  40.                     System.out.println(”Local cookie: ” + cookies.get(i));  
  41.                 }  
  42.                 EntityUtils.consume(response.getEntity());  
  43.             } finally {  
  44.                 response.close();  
  45.             }  
  46.         } finally {  
  47.             httpclient.close();  
  48.         }  
  49.     }  
  50.   
  51. }  
import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of a local HTTP context populated with
 * custom attributes.
 */
public class ClientCustomContext {

    public final static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();

            // Create local HTTP context
            HttpClientContext localContext = HttpClientContext.create();
            // Bind custom cookie store to the local context
            localContext.setCookieStore(cookieStore);

            HttpGet httpget = new HttpGet("http://localhost/");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Pass local context as a parameter
            CloseableHttpResponse response = httpclient.execute(httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                List<Cookie> cookies = cookieStore.getCookies();
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("Local cookie: " + cookies.get(i));
                }
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}


Apache HttpClient4使用教程 基于HttpClient 4.5.2 执行GET请求 CloseableHttpClient httpClient = HttpClients.custom() .build(); CloseableHttpResponse response = httpClient.execute(new HttpGet(&quot;https://www.baidu.com&quot;)); ... 阅读详情

相关推荐

Httpclient4.5详解之源码解析和使用一: 关键执行流程源码解读

前言 作为一个java后端开发,调用http协议的请求一直使用的httpclient,但是对他内部原理却一概不知,由于它使用了连接池来解决连接资源消耗所带来的问题,同时我们在使用时他也隐匿了连接池操作的很多细节,所以若是使用不当势必会带来很多隐藏的坑(诸如CLOSE_WAIT过多造成服务假死之类)所以最近有时间看了他内部源码,特此记录下来。 httpclient当前版本总览: httpc...

派大星的博客 3021

httpClient详解

前言 当我们在实际开发中往往需要用到第三方的数据,比如天气数据、彩票中奖信息数据等等,想通过程序抓取对应的数据信息,我们可以用到Apache旗下的httpclient来解决。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。在本篇中httpclient的版本号为4.5.2,将通过如下几个案例来说...

tianmlin1的博客 1598

HttpClient 4.5 重定向到中文URL出现乱码的解决方案

一、问题描述: 遇到某个 URL A,请求时发现会重定向到某个包含了中文字符的 URL B。原以为只要 HttpClient 开启了自动重定向的功能,下载 A 指向的页面轻而易举,结果却出乎意料。HttpClient 在获取重定向后的 URL B 时出现了中文乱码,导致下载失败,具体报错信息见下图: 二、解决方案 问题的核心在于 ConnectionConfig 对象的 Charse...

magicpenta的博客 2161

【HttpClient4.5中文教程】五. HttpClient执行上下文HttpContext

最初,HTTP是被设计成无状态的,面向请求-响应的协议。然而,现实世界中的应用程序经常需要通过一些逻辑相关的请求-响应交换来保持状态信息。 为了使应用程序能够维持一个过程状态, HttpClient允许HTTP请求在一个特定的执行上下文中来执行--称为HTTP上下文。如果相同的上下文在连续请求之间重用,那么多种逻辑相关的请求可以参与到一个逻辑会话中。HTTP上下文功能和java.util.Map很

要啥自行车 1万+

HttpClient实现原理深度解析

在当今互联网时代,网络通信已经成为各种应用程序不可或缺的一部分。而HttpClient作为一个强大的网络通信库,在现代网络编程中扮演着至关重要的角色。本文旨在深度解析HttpClient的实现原理,以帮助读者更好地理解其工作机制,从而提升网络编程能力。

fudaihb的博客 1502

HTTPClient 4.5:必备Jar包及源码解析

在当今的网络时代,HTTPClient作为一款广泛使用的网络通信客户端库,对于Web开发者而言可谓是不可或缺的工具。本章节将简要介绍HTTPClient的基础知识及其在应用开发中的重要性。HTTPClient是一个开源的Java HTTP客户端库,它提供了访问Web服务器的简易方式。通过它,开发者可以构建HTTP请求、发送请求并接收响应,这些操作都封装在易于理解和使用的API中。超文本传输协议(HTTP)是互联网上应用最为广泛的一种网络协议。

weixin_32445049的博客 929

五、HttpClient执行上下文HttpContext

HttpClientContext context = HttpClientContext.create(); 最初,HTTP是被设计成无状态的,面向请求-响应的协议。然而,现实世界中的应用程序经常需要通过一些逻辑相关的请求-响应交换来保持状态信息。 为了使应用程序能够维持一个过程状态, HttpClient允许HTTP请求在一个特定的执行上下文中来执行--称为HTTP上下文。如果相同的上下文...

bigbighenry的博客 6255

带硬约束的物理信息神经网络(PINN with Hard Constraint)示例及代码

本文以一个案例介绍了带硬约束的物理信息神经网络的原理及实现步骤。

m0_72768523的博客 5359

【HttpClient】HttpClient4.5基础教程

一、前言 1、说明 HttpClient是一个目前最常用的用于模拟客户端发送http请求的工具,可用于接口自动化测试或者爬虫或者在项目中加入获取其他网站数据等; 支持目前所有的请求方式,如put,post,get,delete等; 2、maven依赖添加 maven依赖如下: &amp;amp;amp;lt;dependency&amp;amp;amp;gt; &amp;amp;amp;lt;groupId&amp;amp;amp;gt;org.apache.ht

df0128的专栏 1万+

Case-Based Reasoning用于RAG

在做大模型应用RAG的时候,会发现一种特殊的场景,就是基于之前的case进行回答,比如法律咨询、医疗诊断等等。这种情况的问答,需要有强有力的case支持才行,有了case支持,大模型回答会更加准确。CBR这个概念已经很久了,它是一种人工智能推理方法,它的基本思想是:遇到新问题时,先回忆相似的过去案例,再基于这些案例进行调整,得到新问题的解答。Retrieve(检索):在案例库中找到与当前问题最相似的案例。Reuse(复用):借鉴案例的解决方案来应对当前问题。

sinat_28694519的博客 939

台达B3伺服电机485通讯的调试过程

最近上了一项目,没办法直接把B3伺服接到PLC上去,怎么办?偶说试下直接电脑通过100多米的485线控制好了,定型前的测试就这样展开了。 1、焊CN1口 如果不安装CN1,是开不了机的,要报很多错误,比如SERV EMG ALERT, 上限报警,下限报警什么的,怎么办?直接焊好CN1头子吧,烦了点,但是必要的。 主要接的是11,9,10,32,31,30几个脚,按照图上连接好就是了。 2、 接线路 按照上面的图,接上伺服电机线,编码器线,电源线,包括限位常闭开关、485连线等,就完..

shidong01的博客 1万+

【HttpClient4.5中文教程】【第一章 :基础】1.1执行请求(二)

原文:http://blog.csdn.net/u011179993/article/details/47147909 更多HttpClient4.5中文教程请查看:点击打开链接 ================================================================================================

Ryan Z 的技术日志 610

手机安装Kali Linux

在数字化时代,信息安全和隐私保护显得尤为重要。,作为一款专业的和工具,因其强大的功能和丰富的资源库而受到广大安全研究者和爱好者的青睐。然而,我们通常只能在传统的电脑设备上安装和使用Kali Linux。那么,有没有可能将也变成一款随身携带的Kali Linux设备呢?答案是肯定的。本文将介绍如何在手机上安装Kali Linux,使你的手机变成一款强大的移动安全工具。,我们需要明确一点,手机安装Kali Linux并非简单的操作,需要对手机进行一定的改造和配置。

2301_80124151的博客 6973

httpclient4.5.3 使用

我这里是使用maven来构建项目,用普通工程的请下载相关的包后加入buildpath 。 新建一个maven工程,这里我只是简单的写了两种请求 这里选择勾选建立一个简单工程 红色的地方可以根据需求选择,点击完成。 org.apache.httpcomponents httpclient 4.5.3 log4j

u012410349的博客 7675

VQGAN实战:从文本到高清图像的保姆级生成教程(含PyTorch代码)

本文详细介绍了VQGAN(Vector Quantized Generative Adversarial Network)在文本到高清图像生成中的应用,提供了从环境配置到模型加载、文本编码及图像生成的完整PyTorch代码教程。通过实战案例和高级调优技巧,帮助开发者快速掌握VQGAN的核心技术,实现百万像素级的高清图像生成。

u8v9w0x1y的博客 649

利用李雅普诺夫函数开发航天器姿态控制系统

本文基于李雅普诺夫函数控制方法,采用修正罗德里格斯参数(MRP)描述航天器姿态,设计了姿态控制律。通过构造能量型李雅普诺夫函数,推导出保证系统稳定的控制闭环方程,实现了航天器从初始状态到目标状态的稳定转换。针对MRP参数可能出现的奇异性问题,采用影子集进行规避。仿真实验包含两种模式:非追踪模式(目标状态为0)和追踪模式(目标为三角函数轨迹)。结果表明,该控制方法能够有效实现姿态稳定和轨迹跟踪,在短暂调整后即可精确跟随目标轨迹。控制律设计考虑了不同参考系间的转换,通过DCM矩阵处理目标角速度的坐标变换问题。

weixin_50227659的博客 1223

【HttpClient4.5中文教程】【第一章 :基础】1.1执行请求(三)

原文:http://blog.csdn.net/u011179993/article/details/47172215 更多HttpClient4.5中文教程请查看:点击打开链接 =============================================== 1.1.7.生产实体内容 HttpClient提供了几个类,用来通过HTTP连接高效

Ryan Z 的技术日志 567

Python开发MCP Client

全部例子只是MCP Client访问MCP Server的过程,那么这样其实就失去了MCP协议的创建的初衷,和大模型集成后才能发挥MCP最大的作用。

Criss@陈磊 2973

HttpClient-4.5.2官方教程完整翻译

HttpClient 4.5.2 前言 超文本传输协议(HTTP)可能是当今互联网上使用的最重要的协议。 网络服务,支持网络的设备以及网络计算的发展继续扩大了HTTP协议在用户驱动的Web浏览器之外的作用,同时增加了需要HTTP支持的应用程序的数量。 尽管java.net包提供了通过HTTP访问资源的基本功能,但它并不能提供许多应用程序所需的全部灵活性或功能。 HttpClient试图通过提...

zhujianlin1990的专栏 1625

第十二天:Python字典(Dict)详解

字典(Dictionary)是Python中最强大的数据类型之一,它是一种可变的、无序的键值对(key-value)集合。字典中的元素是通过键(key)来存取的,而不是通过偏移量(如列表中的索引)。 字典的核心特性包括: 键值对结构:每个元素由一个键和一个值组成,中间用冒号(:)分隔 无序性:字典中的元素没有固定的顺序(Python 3.7+版本中字典会保持插入顺序,但不应依赖此特性进行顺序操作) 可变性:可以动态地添加、修改或删除键值对 键的唯一性:字典中的键必须是唯一的,如果重复,后面的键值对会覆盖

本博客聚焦 YOLOv11 全流程落地,涵盖架构优化、数据集处理、训练技巧与多场景部署,兼及国产数据库、Java 开发与 AI 模型应用,内容兼顾理论与工程实践,为开发者提供系统干货,助力高效提升技术能力。 1681

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【HttpClient4.5中文教程】【第一章 :基础】1.5 异常

原文:http://blog.csdn.net/u011179993/article/details/49022519 HttpClient 能够抛出两种类型的异常:1)java.io.IOException :在 I/O 失败时,如socket连接超时或被重置的异常;2)HttpException:标志 HTTP 请求失败的信号,如违反 HTTP 协议。通常 I/O 错误被认为

Ryan Z 的技术日志 605

Statistics and Machine Learning Toolbox

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

【HttpClient4.5中文教程】三.HttpClient执行基本请求

更多HttpClient4.5中文教程请查看:点击打开链接==================================HttpClient最基本的功能是执行HTTP方法,一次 HTTP 方法的执行包含一个或多个 HTTP 请求/响应的交互,通常由 HttpClient的内部来处理。使用者需要提供一个Request对象来执行HTTP请求,HttpClient就会把请求传送给目标服务器并返回一

要啥自行车 1万+

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

HttpClient-4.0.1 官方教程

HttpClient-4.0.1 官方教程写在前头(HttpClient项目现已停产,并且不再开发)项目介绍HttpClient4.0 架构方法发生的变化:第一章 Fundamentals(基础)1.1执行请求1.1.1 HTTPRequest (HTTP请求)1.1.2 HTTPResponse (HTTP响应)1.1.3 Workingwith message headers (处理头部...

bellus 1725

★★ httpclient-3.1 TO HttpClient 4.0.1,httpclient-3.1 升级到HttpClient 4.0.1

httpclient-3.1 TO HttpClient 4.0.1,httpclient-3.1 升级到HttpClient 4.0.1

jackpk的专栏 2139

HttpClient 4.3教程 第一章 基本概念(转载)

1.1. 请求执行 HttpClient最基本的功能就是执行Http方法。一个Http方法的执行涉及到一个或者多个Http请求/Http响应的交互,通常这个过程都会自动被HttpClient处理,对用户透明。用户只需要提供Http请求对象,HttpClient就会将http请求发送给目标服务器,并且接收服务器的响应,如果http请求执行不成功,httpclient就会抛出异样。 下面是

FOTT 770
上一篇: 【HttpClient4.5中文教程】【第一章 :基础】1.2 HttpClient接口
下一篇: httpclient4.5入门教程之连接管理
光与热
博客等级 码龄11年 55粉丝 126原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值