Java4Android之HttpClient入门使用代码集

本文将从代码的角度去引导如何使用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);
            }
        }

    }

}
时间: 2024-08-07 02:00:38

Java4Android之HttpClient入门使用代码集的相关文章

入门初探+伪集群部署

Kafka入门初探+伪集群部署 Kafka是目前非常流行的消息队列中间件,常用于做普通的消息队列.网站的活性数据分析(PV.流量.点击量等).日志的搜集(对接大数据存储引擎做离线分析). 全部内容来自网络,可信度有待考证!如有问题,还请及时指正. 概念介绍 在Kafka中消息队列分为三种角色: producer,即生产者,负责产生日志数据. broker,存储节点,负责按照topic中的partition分区,均匀分布式的存储分区. consumer,即消费者,负责读取使用broker中的分区.

AppleWatch开发入门三——代码交互与控制器生命周期

AppleWatch开发入门三--代码交互与控制器生命周期 一.引言 在前两篇博客中,讨论了关于watch开发中框架与界面布局相关,然而主要的逻辑,终究还是要通过代码来实现的,在我们创建了项目之后,就会生成InterfaceController这个文件,它就是我们storyBoard中的入口视图控制器. 二.代码交互与控制器声明周期 storyBoard中的控件我们可以通过拖拽的方式关联到文件中,Action和Outlet两种关联方式基本可以达到我们修改控件和处理业务逻辑的需求. WKInter

C#连接Access、SQL Server、Oracle、MySQL、DB2和SyBase数据库的代码集

C#连接六类数据库的代码集 本文列出了C#连接Access.SQL Server.Oracle.MySQL.DB2和SyBase六种不同数据库的程序源码和需要注意的点. 1.C#连接Access 程序代码: Code using System.Data;using System.Data.OleDb; .. string strConnection="Provider=Microsoft.Jet.OleDb.4.0;"; strConnection+[email protected]&

【工作常用代码集】批量Telnet远端端口

作者:gnuhpc 出处:http://www.cnblogs.com/gnuhpc/ __author__ = 'gnuhpc' import telnetlib,socket IP={} def parseTel(line): parseArray = line.split() IP[parseArray[0]]=parseArray[1] with open("tel.lst") as f: for line in f: parseTel(line) for (ip,port)

数据库快速入门例子代码

数据库快速入门例子代码 下面的内容将简单说明怎样使用数据库.更详细的信息请阅读各个函数的单独介绍页面. 初始化数据库类 下面的代码将依据你的数据库配置载入并初始化数据库类: $this->load->database(); 一旦被载入,你可以在任何地方像这样使用它: 注意: 如果你的所有页面均要求初始化数据库类,你可以让它自动加载.详见 数据库连接. 多结果标准查询(对象形式) $query = $this->db->query('SELECT name, title, email

js 代码集(学习js的朋友可以看下)

js 代码集 学习js的朋友可以看下,功能比较多,大家可以自己选择. /** * @author Super Sha * QQ:770104121 * E-Mail:[email protected] * publish date: 2009-3-27 * All Rights Reserved */ var JsHelper={}; //声明一个JsHelper根命名空间 JsHelper.DOM = {}; //声明JsHelper目录下的DOM命名空间 JsHelper.Event={};

ReactNative入门(4)代码结构

一.了解index.ios.js 大家都清楚,React-Native就是在开发效率和用户体验间做的一种权衡.React-native是使用JS开发,开发效率高.发布能力强,不仅拥有hybrid的开发效率,同时拥有native app相媲美的用户体验.目前天猫也在这块开始试水. 用编辑器打开index.ios.js文件,分析代码结构: 1.第一句:var React = require('react-native');有Node.js开发经验的同学都清楚,require可以引入其他模块.如果没有

react-native 入门资源合集

# 了解react-native React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. 套用官方的一句话:React Native 让你具备使用JavaScript和React一致的开发经验来构建拥有原生应用体验的世界级应用. 如果

Java4Android之httpclient学习与应用

在Java开发中,不可避免的需要和http打交道.而无论我司的迅雷动漫还是我主导的"搜芽"android客户端开发,都需要使用到http和服务器打交道..虽然Java也提供了http的接口,但据我了解,更多的公司都是使用Apache的httpclient来进行开发,不仅因为它灵活强大,而且便捷. 今天,我们学习httpclient的基础知识. 关于Http的基础,在此就不再复习了.建议大家去看一本权威制作<HTTP权威指南>,加个略贵,109元人民币,不过,我买了,因为经典