Java开源框架类库介绍(一)--HttpComponents

Apache HttpClient 5 使用详细教程 转存失败重新上传取消超文本传输协议(HTTP)可能是当今互联网上最重要的协议之一,Web 服务、微服务以及支持网络的各种设备上的服务几乎都是 HTTP 协议,HTTP 协议已经从 Web 浏览器走向了更广泛的使用场景。虽然java.net包已经提供了 HTTP 访问资源的基本功能,但是它不够灵活,而且不能随心所欲的进行自定义。... 阅读详情

我们在开发过程中经常会使用到HTTP协议作为我们数据交换的协议,本小节主要介绍一个开源的HTTP组件的使用。


1. 环境配置

1.1 下载安装

HTTP Components是Apache的一个子项目,地址是: http://hc.apache.org/,主页中提供下载。使用过程及其简单,解压缩后直接将其lib目录下文件拷贝到classpath下即可。

1.2 使用Maven管理

如果您使用Maven管理你的项目,需要这样配置:

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>${httpcomponents.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>${httpcomponents.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>fluent-hc</artifactId>
			<version>${httpcomponents.version}</version>
		</dependency>


2. 示例代码

2.1 最简单的例子

最简单的例子当然是实现请求的处理,下面分别是GET和POST:
	public void simpleGet() {
		HttpGet get = new HttpGet("http://www.baidu.com");

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(get);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void simplePost() {
		HttpPost post = new HttpPost("http://www.baidu.com");
		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(post);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
注意我的代码使用了JDK 1.7的try语句块新特性,如果低于1.7版本请自行修改代码。


下面是处理响应的代码:
	private void handleResponse(HttpResponse response) throws IOException {
		int statusCode = 0;
		if ((statusCode = response.getStatusLine().getStatusCode()) == 200) {
			HttpEntity entity = response.getEntity();
			System.out.println(entity.getContentType());
			System.out.println(entity.getContentEncoding());
			System.out.println(entity.getContentLength());

			try (InputStream ins = response.getEntity().getContent();) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(ins));
				String str = null;
				while ((str = reader.readLine()) != null) {
					System.out.println(str);
				}
			}
		} else {
			System.out.println("------------http error: statusCode is: "
					+ statusCode);
		}
	}

2.2 增加URI方式

简单的一个请求我们可以处理,那么如果这个请求中需要包含参数呢?下面是代码:
	public void simpleURIGet() throws URISyntaxException {
		URI uri = new URIBuilder().setScheme("http").setHost("www.google.com")
				.setPath("/search").setParameter("q", "httpclient")
				.setParameter("btnG", "Google Search").setParameter("aq", "f")
				.setParameter("oq", "").build();
		HttpGet get = new HttpGet(uri);
		System.out.println(get.getURI());

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(get);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void simpleURIPost() throws URISyntaxException {
		URI uri = new URIBuilder().setScheme("http").setHost("www.google.com")
				.setPath("/search").setParameter("q", "httpclient")
				.setParameter("btnG", "Google Search").setParameter("aq", "f")
				.setParameter("oq", "").build();
		HttpPost post = new HttpPost(uri);
		System.out.println(post.getURI());

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(post);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

对于POST,还可以这样:
	public void simpleParamPost() throws UnsupportedEncodingException {
		HttpPost post = new HttpPost("http://www.baidu.com");

		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("name", "zhangsan"));
		params.add(new BasicNameValuePair("password", "1234"));
		post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(post);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

2.3 对于Header的处理

对于请求头的处理,诸如设置字段值:
	public void addHeadersGet() throws UnsupportedEncodingException {
		HttpGet get = new HttpGet("http://www.baidu.com");
		get.setHeader("User-Agent",
				"Ahopedog/5.0 (Linux NT 5.1; rv:5.0) Gecko/20100101 FireDog/5.0");
		get.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("name", "zhangsan"));
		params.add(new BasicNameValuePair("password", "1234"));

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(get);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addHeadersPost() throws UnsupportedEncodingException {
		HttpPost post = new HttpPost("http://www.baidu.com");
		post.setHeader("User-Agent",
				"Ahopedog/5.0 (Linux NT 5.1; rv:5.0) Gecko/20100101 FireDog/5.0");
		post.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("name", "zhangsan"));
		params.add(new BasicNameValuePair("password", "1234"));
		post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(post);) {
			handleResponse(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

处理响应头的话基本原理差不多,代码是这样:
	public void handlePostResponseHeader() throws UnsupportedEncodingException {
		HttpPost post = new HttpPost("http://www.baidu.com");

		try (CloseableHttpClient httpClient = new DefaultHttpClient();
				CloseableHttpResponse response = httpClient.execute(post);) {
			Header[] headers = response.getAllHeaders();
			for (Header h : headers) {
				System.out.println(h.getName() + " : " + h.getValue());
			}
			Header serverHeader = response.getFirstHeader("server");
			System.out.println(serverHeader.getName() + " : "
					+ serverHeader.getValue());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


通过以上代码可以看出,HTTP component能够帮我们省去复杂的HTTP协议的建立连接、处理等操作,框架封装了细节。


3. Fluent方式

以上工作做完了之后,HTTP component仍然觉得不满足,他们认为还可以提供给我们更简洁编写自己代码的方案,于是Fluent来了:

3.1 最简单的调用

GET和POST都差不多:
	public void simpleGet() {
		Request request = Request.Get("http://www.baidu.com");

		handleContent(request);
	}

	public void simplePost() {
		Request request = Request.Post("http://www.baidu.com");

		handleContent(request);
	}

处理代码:
	private void handleContent(Request request) {
		Response response;
		try {
			response = request.execute();
			System.out.println(response.returnContent());
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

3.2 增加参数

对于GET很简单,这里看看POST:
	public void simpleURIPost() {
		URI uri = URI.create("http://www.sina.com");
		Request request = Request.Post(uri).bodyForm(
				Form.form().add("username", "zhangsan").add("pasword", "pwd")
						.build());

		handleContent(request);
	}

3.3 对于头和整个内容的处理

对于请求头、响应头和整个响应的处理,参见下面的代码:
	public void simpleHeaderPost() {
		Request request = Request.Post("http://www.sina.com.cn");
		request.addHeader("User-Agent",
				"Ahopedog/5.0 (Linux NT 5.1; rv:5.0) Gecko/20100101 FireDog/5.0");
		request.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

		handleResponse(request);
		handleEntity(request);
	}

	private void handleEntity(Request request) {
		try {
			HttpResponse response = request.execute().returnResponse();
			HttpEntity entity = response.getEntity();
			Header header = entity.getContentType();
			System.out.println(header.getName() + ":    " + header.getValue());
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void handleResponse(Request request) {
		try {
			HttpResponse response = request.execute().returnResponse();
			Header[] headers = response.getAllHeaders();
			for (Header header : headers) {
				System.out.println("Header Name: " + header.getName()
						+ "; Header Value: " + header.getValue());
			}
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}





使用Java的HTTP协议库 HttpComponents HTTP协议是在互联网上进行通信的一种规范,它定义了客户端和服务器之间的请求和响应的格式。在Java中,我们可以使用HttpComponents库来处理HTTP协议相关的操作,包括发送HTTP请求和接收HTTP响应。您可以使用HttpComponents库发送HTTP请求并接收HTTP响应,从而实现与服务器之间的数据交互。除了发送GET请求,HttpComponents库还支持发送其他类型的HTTP请求,如POST、PUT、DELETE等。在获取到响应后,我们可以通过获取到响应后,我们可以通过。 阅读详情

相关推荐

深入理解Apache HttpComponents Client

本文还有配套的精品资源,点击获取 简介:Apache HttpComponents Client是Apache软件基金会的开源项目,它提供了一个强大的HTTP客户端库,支持包括HTTP基本方法、连接管理、身份验证、Cookie管理等。本教程将详细介绍如何使用4.4.1版本的HttpComponents Client,包括连接管理、多协议支持、请求响应处理、内置身份验证机制、...

weixin_35516624的博客 1770

Apache HttpComponents 简单使用

官网 https://hc.apache.org/ 参考 https://www.cnblogs.com/lrzy/articles/15667814.html 简介 Apache Commons HttpClient(或被称为 Apache HttpClient 3.x)、Apache HttpComponents Client(或被称为 Apache HttpClient 4.x) HttpComponents 项目就是专门设计来简化 HTTP 客户端与服务器进行各种通讯编程。 现在的 HttpComp

不懂一休 2万+

新手避坑指南:用COMSOL Multiphysics仿真气体放电(汤逊vs.流注)

本文详细介绍了使用COMSOL Multiphysics仿真气体放电的实战指南,涵盖汤逊理论和流注模型的实现方法。通过对比两种放电模型的关键参数和物理场配置,帮助新手避免常见错误,准确预测气体击穿过程。文章还提供了工程应用案例,如高压绝缘子设计优化,展示了仿真技术在电力设备绝缘设计中的实际价值。

weixin_28716181的博客 472

HttpComponents入门解析

  1 简介     超文本传输协议(http)是目前互联网上极其普遍的传输协议,它为构建功能丰富,绚丽多彩的网页提供了强大的支持。构建一个网站,通常无需直接操作http协议,目前流行的WEB框架已经透明的将这些底层功能封装的很好了,如常见的J2EE, .NET, php等框架或语言。 除了作为网站系统的底层支撑,http同样可以在其它的一些场景中使用,如游戏服务器和客户端的传输协议、web...

金永哲的博客 Now Loading... 550

ubuntu安装XXX包时出现(= 20.0.8-0ubuntu1~18.04.1) but it is not going to be installed

安装mujoco_py时,最后一步尝试 import mujoco_py 时出现报错 esashim.c:1:10: fatal error: GL/osmesa.h: No such file or directory 1 | #include <GL/osmesa.h> | ^~~~~~~~~~~~~ compilation terminated. 在https://github.com/openai/mujoco-py#ubuntu-ins

dealexce的博客 1794

对西安交大轴承数据集XJTU-SY_Bearing_Datasets进行读取和处理:

故障诊断,对西安交大轴承数据集XJTU-SY_Bearing_Datasets进行读取和处理

qq_44757503的博客 6060

Maven Maven的概述

随着我们使用越来越多的框架,或者框架封装程度越来越高,项目中使用的jar包也越来越多。项目中, 一个模块里面用到上百个jar包是非常正常的。

weixin_65637841的博客 492

【Codex Sandbox 与审批机制:小白也能看懂的实用教程】

这篇教程介绍了Codex工具中的沙盒(Sandbox)和审批(Approvals)机制,帮助用户安全高效地使用Codex协作。沙盒限制Codex访问范围,审批机制则控制敏感操作权限。文章详细讲解了五种常见模式:最安全的安全只读浏览、只读非交互、仓库内编辑、Auto预设和不推荐的YOLO模式。还提供了新手使用路径建议、配置示例和实战场景范式,包括如何测试沙盒行为、不同系统下的实现方式以及常见问题解答。最后附上速查清单,帮助用户快速选择合适的权限组合。

zsr154278963的博客 6706

HttpComponents和HttpClient基本用法

HttpClient是什么? HTTP 协议是 Internet 上使用得最多、最重要的协议之一,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。 虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。 HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最

azhu12138的博客 3401

命令行驱动视频剪辑:cutcli与AI自动化工作流实战

在视频内容创作领域,自动化与批量化处理是提升生产效率的关键。传统图形界面工具在应对重复性任务时往往效率低下,而通过命令行接口(CLI)驱动视频生成,则能实现流程的程序化控制。其技术原理在于将视频结构抽象为可编程的指令序列,通过解析命令生成标准化的工程文件。这种模式的核心价值在于将视频制作从手动操作转变为代码驱动,特别适合与AI编程助手集成,实现自然语言到视频草稿的自动转换。应用场景广泛覆盖社交媒体内容批量生产、教育视频自动化生成、数据可视化视频组装等领域。本文以cutcli工具为例,深入解析如何通过命令行与

weixin_42520239的博客 576

【项目实战】Qt6 录制屏幕、录制声音生成MP4、AVI、MA3等(完整源码,可直接编译使用)

本文将详细介绍如何利用Qt6多媒体模块中的QMediaCaptureSession、QMediaRecorder、QScreenCapture、QAudioInput、QMediaFormat等功能,实现对屏幕和声音的录制,并生成常见的媒体格式文件,如MP4、AVI、MA3等。我们将探讨如何利用这些功能来实现灵活的视频和音频参数设置,以满足不同需求下的录制和生成要求。我们将重点讨论如何配置视频和音频参数,包括分辨率、帧率、编解码器选择、音频采样率、声道设置等。

yegu001的博客 4939

apache的HttpComponents项目的介绍和简单使用

1、HttpComponents项目的介绍 先介绍一下一个开源项目, 这个项目就是Apache开源组织中的HttpComponents,主要是提供对http服务器的访问功能,目前已经是一个单独的项目,可见http服务器的访问绝非易事。     在某些时候可能需要通过程序来访问这别人的网页程序,比如从别人的网页中“偷”一些数据。如果对方仅仅是一个很简单的页面,那我们的程序

Mr_Lee—胜利的博客 462

GPD源码分析

gpd使用示例 先看下面一段代码,为标准gpd算法的使用方法,可以看到输入为点云,cloud_camera_; 输入:std::unique_ptr<gpd::util::Cloud> cloud_camera_ 输出: std::vector<std::unique_ptr<gpd::candidate::Hand>> grasps; // detect grasp poses gpd对象:std::unique_ptr<gpd::GraspDetect.

weixin_41003113的博客 2332

Apache HttpComponents Core 开源项目指南及问题解决

Apache HttpComponents Core 开源项目指南及问题解决 Apache HttpComponents Core 是Apache软件基金会的一个重要项目,专注于提供高效、灵活的HTTP客户端和服务端通信组件。此项目以Java作为主要编程语言,广泛应用于构建需要进行HTTP通信的应用程序。 新手使用注意事项及解决方案 1. 环境配置问题 问题描述: 新手在搭建开发环境时可能会因为J...

gitblog_00881的博客 417

华为OD机试双机位C卷-几何平均值最大子数组(Py/Java/C/C++/Js/Go)

华为OD机试(机考)2026双机位C卷 【几何平均值最大子数组】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【几何平均值最大子数组】。

qq_45776114的博客 1367

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

HttpComponents-Client 4.4 二进制包下载

HttpComponents-Client 4.4 二进制包下载 去发现同类优质开源项目:https://gitcode.com/ 欢迎使用HttpComponents-Client 4.4的二进制资源文件下载。此压缩文件包含了HttpComponents-Client组件的JAVA实现,它是一个开放源代码的项目,旨在为JAVA应用程序提供一个功能强大、灵活且高效的HTTP客户端。 关于HttpC...

gitblog_06750的博客 1116

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

HttpComponents-Client 4.4 二进制包下载:强大的JAVA HTTP客户端

HttpComponents-Client 4.4 二进制包下载:强大的JAVA HTTP客户端 去发现同类优质开源项目:https://gitcode.com/ HttpComponents-Client 4.4 二进制包下载,为JAVA应用程序提供功能强大、灵活且高效的HTTP客户端。 项目介绍 HttpComponents-Client 是Apache软件基金会下的Jakarta Commo...

gitblog_06798的博客 869

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

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Apache HttpComponents HttpClient

是 Apache 提供的一个开源库,用于在 Java 应用程序中执行 HTTP 请求和响应处理。它支持同步和异步模式,提供了对常见 HTTP 操作的简单而强大的封装。类封装的请求体或响应体可以承载任何格式的数据,传递给服务器或从服务器接收。实体可以理解为 HTTP 请求或响应的“数据负载”。

2301_79140115的博客 889

Apache HttpComponents 项目教程

Apache HttpComponents 项目教程 项目介绍 Apache HttpComponents 是一个开源项目,旨在提供构建HTTP服务的组件。该项目由Apache软件基金会维护,自2005年以来一直在开发和改进。HttpComponents 包括多个子项目,如HttpClient和HttpCore,它们分别提供了客户端和服务器端的HTTP通信功能。 项目快速启动 环境准备 在开始之前...

gitblog_00542的博客 833

HttpComponents 发送post get 请求

1.场景描述   使用Apache开源组织中的HttpComponents,完成对http服务器的访问功能,消息体xml报文。 2.HttpComponents项目的介绍   HttpComponents项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方...

dianluochai5713的博客 284

HttpComponents

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34319640的博客 95

探索JIRA的Java世界:jira-client开源项目推荐

探索JIRA的Java世界:jira-client开源项目推荐 项目介绍 在现代软件开发中,JIRA作为项目管理和问题跟踪工具,被广泛应用于各种开发团队中。然而,与JIRA的交互通常需要通过复杂的API调用,这对于开发者来说可能是一个挑战。为了简化这一过程,jira-client应运而生。jira-client是一个轻量级的JIRA REST客户端库,专为Java开发者设计,旨在提供简单、直观的J...

gitblog_00474的博客 993

Java开源的爬虫工具--对比

本文介绍Java开源的爬虫工具(框架)。

IT利刃出鞘的博客 1097

Apache HttpComponents Client详解

Apache HttpComponents Client(也称为HttpClient)是一个开源的Java库,用于发送HTTP请求并处理HTTP响应。它提供了一组易于使用的API,用于构建和执行HTTP请求,并处理请求和响应的各个方面,如URL处理、请求头、请求体、响应状态、响应内容等。这些只是Apache HttpComponents Client库的一些基本用法示例,它还提供了许多其他功能和配置选项,如连接池管理、代理设置、超时设置、SSL/TLS配置等,以满足更复杂的HTTP请求需求。

wei7a7a7a的博客 533

推荐开源项目:Apache HttpComponents Core

推荐开源项目:Apache HttpComponents Core 项目介绍 欢迎关注Apache HttpComponents项目中的HttpCore组件。这是一个专门设计用于处理HTTP协议的核心库,提供了高效且可扩展的HTTP客户端和服务器端实现。该项目旨在简化网络通信并提供对Java平台的强大支持。 项目技术分析 HttpCore依赖于Java 1.6及以上版本的运行时环境。它针对HTTP...

gitblog_00059的博客 486
上一篇: Maven项目管理实战(六)--完成单元测试
下一篇: Java开源框架类库介绍(二)--FastJson
Soloman
博客等级 码龄25年 171粉丝 159原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值