Apache HttpClient4.2.5 模拟post、登录并访问验证授权数据

1.HttpClient 简介

                  (百度文库)HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 HTTPClient,然后根据作者实际工作经验给出了一些常见问题的解决方法。

HttpClient下载地址:

                      http://hc.apache.org/downloads.cgi

                      我们选择:HttpClient 4.2.5 (GA)(4.2.5.zip)(下载binary就可以了,不用source)

2.使用方式:

                      下载完成后解压zip包,在\httpcomponents-client-4.2.5-bin\httpcomponents-client-4.2.5\lib下可以看到所有的包都在里面了,我们接下来的例子中使用其中3个包,分别是:

         httpcore-4.2.4.jar

         httpclient-4.2.5.jar

         commons-logging-1.1.1.jar

         将这3个jar包添加到项目中,然后简单封装HttpClient类如下:

package com.test;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.*;

public class HT {
    HttpClient httpclient=new DefaultHttpClient();
    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public String post(String url,String respEncoding) {
        return post(url,"UTF-8",respEncoding,new ArrayList<NameValuePair>());
    }

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public String post(String url,String reqEncoding,String respEncoding,List<NameValuePair> param) {
        String resStr = "";
        // 创建httppost
        HttpPost httppost = new HttpPost(
                url);
        // 创建参数队列
        List<NameValuePair> formparams = param;
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, reqEncoding);
            httppost.setEntity(uefEntity);
            HttpResponse response;
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resStr = EntityUtils.toString(entity,respEncoding);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
           // httpclient.getConnectionManager().shutdown();
        }
        return resStr;
    }

    /**
     * 发送 get请求
     */
    public String get(String url) {
        //httpclient = new DefaultHttpClient();
        String resStr = "";
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            HttpResponse response = httpclient.execute(httpget);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 打印响应状态
            System.out.println(response.getStatusLine());
            if (entity != null) {
                // 打印响应内容长度
//                System.out.println("Response content length: "
//                        + entity.getContentLength());
                // 打印响应内容
//                System.out.println("Response content: "
//                        + EntityUtils.toString(entity));
                resStr=EntityUtils.toString(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            //httpclient.getConnectionManager().shutdown();
        }
        return resStr;
    }

调用:

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-7-25
 * Time: 下午4:05
 * To change this template use File | Settings | File Templates.
 */
public class MainClass {
    public static void main(String[] args) {
        HT ht = new HT();//构造参数
        List<NameValuePair> list =new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("li", "house"));//登录参数

        System.out.println(ht.post("http://localhost:2375/Default.aspx", "UTF-8", "UTF-8", list));//先post登录也卖弄
        System.out.println(ht.get("http://localhost:2375/WebForm1.aspx"));//此页面是需要登录才能访问的页面
    }
}


注意点:NameValuePair和BasicNameValuePair都是httpclient包里的,自动生成时可能给你添加jdk中的,需要手动改一下。

3.最后

1.HttpClient支持SSL连接,代码请另百度

2.//httpclient.getConnectionManager().shutdown();被屏蔽掉和HttpClient httpclient=new DefaultHttpClient();定义为全局变量的原因就是这样才能保证第一次post登录之后,第二次访问页面不会提示未登录,通俗的讲只要HttpClient的实例没有重新赋值,它会自动保存cookie,下次访问将自动附带上。



猜你喜欢

转载自blog.csdn.net/juyangjia/article/details/9471113