Java4Android之HttpClient入门使用代码集

Android学习笔记:HttpClient和HttpURLConnection 在Android开发中网络请求是最常用的操作之一,Android SDK中对HTTP(超文本传输协议)也提供了很好的支持,这里包括两种接口: (1)标准Java接口(java.NET)——HttpURLConnection,可以实现简单的基于URL请求、响应功能; (2)Apache接口(org.apache.http)——HttpClient,使用起来更方便更强大; 一、HttpClient H... 阅读详情

本文将从代码的角度去引导如何使用httpclient的各个功能和特性。

第一个程序

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {
  
  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
    		new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}


模拟http网页登入

package org.apache.http.examples.client;

import java.net.URI;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
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;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class ClientFormLogin {

    public static void main(String[] args) throws Exception {
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        try {
            HttpGet httpget = new HttpGet("https://someportal/");
            CloseableHttpResponse response1 = httpclient.execute(httpget);
            try {
                HttpEntity entity = response1.getEntity();

                System.out.println("Login form get: " + response1.getStatusLine());
                EntityUtils.consume(entity);

                System.out.println("Initial set of cookies:");
                List<Cookie> cookies = cookieStore.getCookies();
                if (cookies.isEmpty()) {
                    System.out.println("None");
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        System.out.println("- " + cookies.get(i).toString());
                    }
                }
            } finally {
                response1.close();
            }

            HttpUriRequest login = RequestBuilder.post()
                    .setUri(new URI("https://someportal/"))
                    .addParameter("IDToken1", "username")
                    .addParameter("IDToken2", "password")
                    .build();
            CloseableHttpResponse response2 = httpclient.execute(login);
            try {
                HttpEntity entity = response2.getEntity();

                System.out.println("Login form get: " + response2.getStatusLine());
                EntityUtils.consume(entity);

                System.out.println("Post logon cookies:");
                List<Cookie> cookies = cookieStore.getCookies();
                if (cookies.isEmpty()) {
                    System.out.println("None");
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        System.out.println("- " + cookies.get(i).toString());
                    }
                }
            } finally {
                response2.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

多表单Post示例


/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

用ResponseHandler来简化对http response的处理和资源释放

/**
 * This example demonstrates the use of the {@link ResponseHandler} to simplify
 * the process of processing the HTTP response and releasing associated resources.
 */
public class ClientWithResponseHandler {

    public final static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://localhost/");

            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                public String handleResponse(
                        final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        } finally {
            httpclient.close();
        }
    }

}

多线程环境下GET方法的使用示例

/**
 * An example that performs GETs from multiple threads.
 *
 */
public class ClientMultiThreadedExecution {

    public static void main(String[] args) throws Exception {
        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);

        CloseableHttpClient httpclient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();
        try {
            // create an array of URIs to perform GETs on
            String[] urisToGet = {
                "http://hc.apache.org/",
                "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/",
            };

            // create a thread for each URI
            GetThread[] threads = new GetThread[urisToGet.length];
            for (int i = 0; i < threads.length; i++) {
                HttpGet httpget = new HttpGet(urisToGet[i]);
                threads[i] = new GetThread(httpclient, httpget, i + 1);
            }

            // start the threads
            for (int j = 0; j < threads.length; j++) {
                threads[j].start();
            }

            // join the threads
            for (int j = 0; j < threads.length; j++) {
                threads[j].join();
            }

        } finally {
            httpclient.close();
        }
    }

    /**
     * A thread that performs a GET.
     */
    static class GetThread extends Thread {

        private final CloseableHttpClient httpClient;
        private final HttpContext context;
        private final HttpGet httpget;
        private final int id;

        public GetThread(CloseableHttpClient httpClient, HttpGet httpget, int id) {
            this.httpClient = httpClient;
            this.context = new BasicHttpContext();
            this.httpget = httpget;
            this.id = id;
        }

        /**
         * Executes the GetMethod and prints some status information.
         */
        @Override
        public void run() {
            try {
                System.out.println(id + " - about to get something from " + httpget.getURI());
                CloseableHttpResponse response = httpClient.execute(httpget, context);
                try {
                    System.out.println(id + " - get executed");
                    // get the response body as an array of bytes
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        byte[] bytes = EntityUtils.toByteArray(entity);
                        System.out.println(id + " - " + bytes.length + " bytes read");
                    }
                } finally {
                    response.close();
                }
            } catch (Exception e) {
                System.out.println(id + " - error: " + e);
            }
        }

    }

}






httpclient模拟登陆(使用js设置cookie) 最近做智能终端课的大程,要在android上利用httpclient模拟登陆学校的bbs,因为网络、html协议、脚本语言都还没学,所以查看了很多东西,可算弄出来了。 模拟登陆之前也做过,但是上次的bbs是通过服务器返回的响应(response)的header中set-cookie设置下次访问的cookie,在这种情况下httpclient是可以自动管理cookie的,因此只要先post登陆的表 阅读详情

相关推荐

HttpClient在Android新API上的java.lang.NoSuchFieldError: No static field INSTANCE问题

HttpClient的问题使用中问题问题出现的情况解决的办法总结: 使用中问题 虽然现在都不用httpClient了,但不排除有的小伙像我一样,老项目用到了,还让维护的。哎,说来这是真的坑啊,这都好久之前就废弃的包了,为什么还要用啊,真是搞不懂啊, 如果你出现下面的问题,恭喜你入坑了。 java.lang.NoSuchFieldError: No static field INSTANCE of ...

honeylife的博客 2327

Java4Android之httpclient学习与应用

在Java开发中,不可避免的需要和http打交道。而无论我司的迅雷动漫还是我主导的“搜芽”android客户端开发,都需要使用到http和服务器打交道。。虽然Java也提供了http的接口,但据我了解,更多的公司都是使用Apache的httpclient来进行开发,不仅因为它灵活强大,而且便捷。 今天,我们学习httpclient的基础知识。 关于Http的基础,在此就不再复习了。建议大家去看

MiniMicall的专栏 1503

httpClient和URLConnection的区别

在android项目中,经常需要用到网络,而在联网之前前,我们都要做一次网络的判断,判断当前的网络状态是否可用,然后开始请求网络。 android中请求网络方式有:HttpURLConnection和HttpClient

Android HTTP 请求方式 HttpClient

环境准备 Java 开发时,后台的 Http 请求操作通常使用的是 org.apache.http.client.HttpClient,Android 开发同样可以使用这些第三方 API。 单纯就使用 Apache 的 HttpCLient 来说,Android 编码 与 Java 编码中 API 使用都是基本一样。 HttpClient 依赖 本人使用的是 Android Studio...

蚩尤后裔-汪茂雄 3340

HttpClient使用小结

NULL 博文链接:https://newtime.iteye.com/blog/459662

VisionPro 9.0 QuickBuild里用C#脚本调用Halcon 23.11模型,保姆级图文配置流程

本文详细介绍了如何在VisionPro 9.0 QuickBuild环境中使用C#脚本调用Halcon 23.11深度学习模型,提供从环境配置到模型集成的保姆级图文教程。重点解决图像格式转换、许可证配置等工业视觉检测中的常见问题,帮助开发者快速实现高效、稳定的视觉检测流水线部署。

weixin_27027459的博客 437

android 调用java url地址_HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection...

查看原文:http://blog.youkuaiyun.com/sinat_29912455/article/details/511222861、客户端连接服务器实现内部的原理:分析上图,步骤如下:第一步:在浏览器客户端中得到用户输入的内容。第二步:浏览器得到这个网址之后,内部会将这个域名发送到DNS上,进行域名解析。得到它的IP之后就会链接到指定的服务器上,假如服务器的地址是:221.104.13.32:8...

weixin_39920629的博客 631

2025美赛E题为农业留出空间(附代码+全保姆教程)Making Room for Agriculture

有机农业的核心在于减少化学投入,促进自然控制和可持续性。变量定义CCC: 作物种群III: 害虫种群PPP: 天然捕食者种群(蝙蝠、鸟类等)BBB: 生物多样性水平(以种类数量表示)SSS: 土壤健康指数(影响植物繁殖与作物生长)EEE: 农业生态系统的整体稳定性。

博客 1495

java httpclient posbody,Android平台下轻量级http网络传输库

AsyncHttpHelp是一个android平台下基于httpclient开发的HTTP网络请求工具。优点功能齐全,提供常用的http网络访问接口。轻量级,无任何第三方库依赖,库大小为90K左右。定制化,自定义json解析库,支持请求参数,返回内容预处理。易用性,简单易用,只需几行代码即可完成请求,可随意设置cookie、http头部等信息。功能1、普通get请求2、普通post请求3、Form...

weixin_35733151的博客 198

013 PID参数整定:Ziegler-Nichols法

几年前在调试一台伺服压机,客户要求位置精度±0.01mm,响应时间小于50ms。我按照教科书上的经验值设了P=1.5,I=0.02,D=0.01,结果电机一启动就开始尖叫,位置超调直接干到0.3mm,然后开始震荡,像极了喝醉的舞者。现场工程师看我的眼神,就像在看一个刚毕业的实习生。那次之后我明白了一个道理:PID参数不是靠猜的,也不是靠经验公式硬套的。你需要一个系统的方法,而Ziegler-Nichols法就是那个让你从“瞎调”走向“有章可循”的起点。

m0_50546716的博客 101

Cesium.Ray 知识详解,示例代码

Cesium.Ray 是 CesiumJS 中用于表示三维空间中无限射线的核心类,广泛应用于地理信息系统(GIS)、三维可视化和碰撞检测等场景。射线由起点(origin)和方向向量(direction)定义,数学表达式为 ( P(t) = \text{origin} + t \times \text{direction} )。核心属性包括起点和方向向量,常用方法包括射线与平面的交点计算、根据距离获取射线上的点等。在 Cesium 中,Cesium.Ray 常用于地形碰撞检测、鼠标点选对象和雷达探测模拟等场景

大剑师兰特的GIS世界 425

HTTP基础与Android之——使用HttpClient和HttpURLConnection

1客户端连接服务器实现内部的原理 GET方式和POST方式的差别 HTTP返回请求数据的三种方式 2使用HTTP协议访问网络 3HttpCient 简单来说用HttpClient发送请求接收响应都很简单只需要五大步骤即可要牢记 4DefaultHttpClient GET方式 POST方式 5Java中使用HTTPHttpURLConnection GET方式 POST方式1、客户端连接服务器实现内

壮少Bryant的博客 1万+

节省人力成本40%!仓储物流AI机器人调度系统实战案例(含路径规划算法与系统架构图)

首先,我们需要定义一个Node类self.x = x # 节点x坐标self.y = y # 节点y坐标self.g = g # 从起点到当前节点的实际成本(g值)self.h = h # 从当前节点到终点的启发式成本(h值)self.f = g + h # 总成本(f值)self.parent = None # 父节点(用于回溯路径)self.task_id = task_id # 任务IDself.priority = priority # 任务优先级(1=最高,5=最低)

小程序开发 950

【Android】【嘿!Java】Android工程、Java工程中通过HttpClient请求网络数据的不同方式

最近,写App时遇到了一个奇怪的问题:博主的App中需要向服务器以GET方式发送网络请求,之前博主没怎么写过这方面的代码,为了方便调试,就建了一个Java工程,

爱臭美的程序猿 2312

史上最牛逼的导航网站(很全很详细)

今天,给大家推荐47个聚合型的导航网站 每一个都收录上百个网站,1个能顶100个,丝毫没有夸张的成分。 (推荐收藏) 设计师导航网站 01 优设导航 https://hao.uisdc.com/ 设计师必备的导航网站,包含设计工具、素材资源、字体设计、配色方案、酷站模板等。 界面清晰无广告,收录网站超过520个。 02 设计导航 http://h...

孙叫兽的博客 7万+

100天精通Python(爬虫篇)——第122天:基于selenium接管已启动的浏览器(反反爬策略)

100天精通Python(爬虫篇)——第122天:基于selenium接管已启动的浏览器(反反爬策略)

努力让自己发光,对的人才能迎着光而来 13万+

安卓开发-HttpClient使用

http://blog.youkuaiyun.com/imzoer/article/details/9447985 http://blog.youkuaiyun.com/imzoer/article/details/9447985 http://blog.youkuaiyun.com/imzoer/article/details/9447985 安卓开发-HttpClie

981

ESP32S3 TLS 握手WIFI可用但是在蜂窝热点下卡死:排查方法与根因

设备卡在等。

摸鱼专家 86

在Android中使用HttpClient 4.3.x出现NoSuchFieldError的问题

升级了 HttpClient 前几天看到Apache新发布了 HttpClient 4.3.5,一时手残,将我写的开源项目nForumSDK中的 HttpClient 升级了。 在纯Java的环境下测试了一下,没发现什么问题,新的包还挺好用的,于是就发布了。 过了两天,有人给我发反馈,说在Android应用上测试的时候报错: java.lang.NoSuchFieldError:org.a

dss886的专栏 1167

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

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Android入门:用HttpClient模拟HTTP的GET和POST请求

一、HttpClient介绍 HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器; Android已经集成了HttpClient,因此可以直接使用; 注:此处HttpClient代码不只可以适用于Android,也可适用于一般的Java程序; HTTP GET核心代码: (1)DefaultHttpCli

xiazdong 1万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

android:基于Apache的HttpClient简单使用方法

1.HttpClient HttpClient 是Apache Jakarta Common 下的子项目,在android中已经集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。 2.为什么要使用HttpClient? 相较于HttpURLClient而言,使用HttpClien...

Lzinner的博客 2236

安卓使用HttpClient进行Http Post文件上传

项目有个需求就是需要上传文件,由于传文件要用到multipart/data-form这种content-type。 里面内容全是2进制,各个field需要自己去拼。今天上午用java的HttpUrlConnection那个类自己去做,结果一上午都没做出来,服务器一直报错,拿浏览器提交就一点问题也没有。对比浏览器的报文,眼睛都看花了也没觉得哪里不一样。于是下午就开始尝试HttpClient。 在

小龙同学的博客 1188

android 登录Javaeye(使用HttpURLConnection和HttpClient)

之前在网上看过好多人用java写登录网站,这次正好学习android,自己写实习一个,就拿经常登录的javaeye(现在叫iteye,已经是csdn的了)试一下。 先来分析javaeye登录界面 查看源文件 账号

dellheng的专栏 2620

HttpClient 使用简单案例(scala 版本)

HttpClient 使用简单案例(scala 版本) 1. 背景 1.1 概述 在常见的客户端服务器模型中,最开始是BS模型,也就是browser和server模型,因为最开始都是电脑,浏览器访问占据主流地位。阿里巴巴,京东都是先从网站做起的。 之后的模型变成了cs模型,client客户端,server服务器。这是由于互联网兴起,各种移动客户端流量开始占据主流,如手机,平板,甚至手表,汽车都可以访问网络。 在这个过程中,作为企业级开发语言主流的java,也出现了很多网络请求库,其中比较有历史的就是htt

xiaohu21的博客 1389

java模拟安卓get请求,Android入门:用HttpClient模拟HTTP的GET和POST请求

一、HttpClient介绍HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器;Android已经集成了HttpClient,因此可以直接使用;注:此处HttpClient代码不只可以适用于Android,也可适用于一般的Java程序;HTTP GET核心代码:(1)DefaultHttpClient client = new DefaultHttpCl...

weixin_42300927的博客 445
上一篇: Java4Android之httpclient学习与应用
下一篇: Java4Android之APP自动升级
minimicall
博客等级 码龄18年 407粉丝 174原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值