文档章节

httpClient----java基础

李光正
 李光正
发布于 2015/10/15 14:53
字数 570
阅读 17
收藏 0

在http请求失败是要进行下列操作:

if (response.getStatusLine ().getStatusCode () != 200) {  
        get.abort(); 
        return null; 
 }

HttpGet操作:

public final static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.apache.org/");
            System.out.println("executing request " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            InputStream inSm = entity.getContent();
            Scanner inScn = new Scanner(inSm);
            while (inScn.hasNextLine()) {
                System.out.println(inScn.nextLine());
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }

读取response响应内容部分,也可以借助于 httpcore-4.1.2.jar 里面的:

public class Demo1 {

    /**
     * 用 get 方法访问 www.apache.org 并返回内容
     *
     * @param args
     */
    public static void main(String[] args) {
        //创建默认的 HttpClient 实例
        HttpClient httpClient = new DefaultHttpClient();
        try {
            //创建 httpUriRequest 实例
            HttpGet httpGet = new HttpGet("http://www.apache.org/");
            System.out.println("uri=" + httpGet.getURI());

            //执行 get 请求
            HttpResponse httpResponse = httpClient.execute(httpGet);

            //获取响应实体
            HttpEntity httpEntity = httpResponse.getEntity();
            //打印响应状态
            System.out.println(httpResponse.getStatusLine());
            if (httpEntity != null) {
                //响应内容的长度
                long length = httpEntity.getContentLength();
                //响应内容
                String content = EntityUtils.toString(httpEntity);

                System.out.println("Response content length:" + length);
                System.out.println("Response content:" + content);
            }

            //有些教程里没有下面这行
            httpGet.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
    }
}

分析请求包中这六个头信息: httpget.setHeader("Accept-Encoding""gzip, deflate")可能产生乱码

/**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.iteye.com");

            httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
            httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");
            httpget.setHeader("Accept-Encoding", "gzip, deflate");
            httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
            httpget.setHeader("Host", "www.iteye.com");
            httpget.setHeader("Connection", "Keep-Alive");

            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            InputStream inSm = entity.getContent();
            Scanner inScn = new Scanner(inSm);
            while (inScn.hasNextLine()) {
                System.out.println(inScn.nextLine());
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }
    }

HttpPost操作:

public class Demo2 {

    /**
     * 用post方法访问本地应用根据传递参数不同,返回不同结果
     *
     * @param args
     */
    public static void main(String[] args) {
        //创建默认的 HttpClient 实例
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("http://localhost:86/test1Servlet");

        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("param1", "***"));
        UrlEncodedFormEntity urlEncodedFormEntity;

        try {
            urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            System.out.println("execurting request:" + httpPost.getURI());
            HttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String content = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("Response content:" + content);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
    }
}


本文转载自:http://blog.csdn.net/liguangzhenghi/article/details/7967795

共有 人打赏支持
李光正
粉丝 5
博文 64
码字总数 0
作品 0
大兴
Android 使用自带的HttpClient进行https请求出现403的解决过程记录

出现的过程 最近在用程序模拟一个web站的https登录,然后进行一些后续操作的小玩意。先使用java程序写测试代码,测试通过移植到android。 java基于httpclient-4.3.1.jar开发。 android端使用...

atearsan
2014/03/05
0
1
httpclient4.4 出现NoHttpResponseException的异常解决

httpclient4.4简单初始化httpclient的方式: 使用连接池初始化httpclient的方式: 但在测试过程中发现,有时候出现如下的异常,但重试一次就没有问题: 网上查了相关的报错信息,找到官网上的...

一路向北的兔斯基
2015/07/30
0
1
Java HTTP 组件库选型看这篇就够了

原文出处:行思錄 Java HTTP 组件库选型看这篇就够了 最近项目需要使用 Java 重度调用 HTTP API 接口,于是想着封装一个团队公用的 HTTP client lib. 这个库需要支持以下特性: 连接池管理,...

行思錄
09/25
0
0
使用jetty 自带的http client!

一般情况下我们需要使用HttpClient时可供选择的技术有: 1、HttpURLConnection 2、Apache HttpClient 其他的除了写Socket 我都没有用过了。 偶然的机会发现Jetty 里面也自带了一个HttpClien...

一堆BUG
2012/02/27
0
0
Android 浅谈HttpClient工具类

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的...

Jonson
2013/07/25
0
3

没有更多内容

加载失败,请刷新页面

加载更多

TypeScript基础入门之JSX(一)

转发 TypeScript基础入门之JSX(一) 介绍 JSX是一种可嵌入的类似XML的语法。 它旨在转换为有效的JavaScript,尽管该转换的语义是特定于实现的。 JSX在React框架中越来越受欢迎,但此后也看到了...

durban
23分钟前
0
0
JavaScript使用原型判断对象类型

1. constructor属性 在JavaScript创建对象(二)——构造函数模式中,我们说过可以使用对象的constructor属性判断对象的类型:p1.constructor === Person,可能当时就有细心的读者会想,我们...

Bob2100
25分钟前
1
0
10-《深度拆解JVM》JVM是怎么实现invokedynamic的?(下)

一、问题引入 上回讲到,为了让所有的动物都能参加赛马,Java 7 引入了 invokedynamic 机制,允许调用任意类的“赛跑”方法。不过,我们并没有讲解 invokedynamic,而是深入地探讨了它所依赖...

飞鱼说编程
45分钟前
2
0
457. Circular Array Loop

Description Difficulty : Medium You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's n......

52iSilence7
今天
1
0
MySQL SQL 常见用法

某字段重复记录 select a.fieldA from tableA a group by a.fieldA having count(a.fieldA)>1;==select * from (select a.fieldA, count(1) as faCount from tableA a group......

园领T
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部