HttpClient简单用法

httpClient工具类,包括客户端登陆,post,get请求


import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;

public class HttpUtils {

    private static String url="";
    private static String testURL="";
    //private static String cookieString="$Version=0; JSESSIONID=75C80CE32888521C3CBBF290FBE0C0B6; $Path=/prot";
    private static String cookieString="";
    private static Cookie cookie;

    /**
     * 模拟浏览登陆,登陆成功记录cookie,下次请求的时候带上cookie,防止服务器因未登陆而拒绝请求
     * @param url
     * @param param
     */
    public static void login(String url,Map<String,String> param){
        HttpClient httpClient = new HttpClient();
        String queryString="";
        if(param!=null){
            for (Map.Entry<String, String> entry : param.entrySet()) {
                queryString+=entry.getKey()+"="+entry.getValue()+"&";
            }
            queryString+="timestap="+System.currentTimeMillis();
        }
        url=url+"?"+queryString;
        GetMethod getMethod = new GetMethod(url);
        byte[] responseBody = null;
        try {
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
            int statusCode = httpClient.executeMethod(getMethod);
            Cookie[] cookies = httpClient.getState().getCookies();
            if(cookies.length>0){
              cookie=cookies[0];
              cookieString="$Version="+cookie.getVersion()+"; JSESSIONID="+cookie.getValue()+"; $Path="+cookie.getPath();
              System.out.println(cookieString);
            }
            if(HttpStatus.SC_OK==statusCode){
                InputStream in = getMethod.getResponseBodyAsStream();
                if (in != null) {
                    byte[] tmp = new byte[4096];
                    int bytesRead = 0;
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
                    while ((bytesRead = in.read(tmp)) != -1) {
                        buffer.write(tmp, 0, bytesRead);
                    }
                    responseBody = buffer.toByteArray();
                }
            }
            System.out.println(new String(responseBody,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }
    }
    
    /**
     * get请求
     * @param url
     * @return
     */
    public static String get(String url,Map<String,String> param){
        HttpClient httpClient = new HttpClient();
        String queryString="";
        if(param!=null){
            for (Map.Entry<String, String> entry : param.entrySet()) {
                queryString+=entry.getKey()+"="+entry.getValue()+"&";
            }
            queryString+="timestap="+System.currentTimeMillis();
        }
        url=url+"?"+queryString;
        GetMethod getMethod = new GetMethod(url);
        httpClient.getState().addCookie(cookie);
        byte[] responseBody = null;
        String responseString="";
        try {
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
            int statusCode = httpClient.executeMethod(getMethod);
            if(HttpStatus.SC_OK==statusCode){
                InputStream in = getMethod.getResponseBodyAsStream();
                if (in != null) {
                    byte[] tmp = new byte[4096];
                    int bytesRead = 0;
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
                    while ((bytesRead = in.read(tmp)) != -1) {
                        buffer.write(tmp, 0, bytesRead);
                    }
                    responseBody = buffer.toByteArray();
                }
            }else{
                System.out.println("网络状态异常");
            }
            responseString= new String(responseBody,"UTF-8");
            responseBody=null;
        }  catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查请求地址!");
            e.printStackTrace();
        } catch (IOException e) { //发生网络异常
            System.out.println("网络连接异常!");
            e.printStackTrace();
        } finally {
            //释放连接
            getMethod.releaseConnection();
        }
        return responseString;
    }
    
    /**
     * post请求
     * @param url
     * @param param
     */
    public static String post(String url,Map<String,String> param){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        //postMethod.addRequestHeader("Cookie", cookieString);
        httpClient.getState().addCookie(cookie);
        for (Map.Entry<String, String> entry : param.entrySet()) {
            postMethod.addParameter(entry.getKey(),entry.getValue());
        }
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());//使用系统提供的默认的恢复策略
        byte[] responseBody = null;
        String responseString="";
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            InputStream in = postMethod.getResponseBodyAsStream();
            if (statusCode == HttpStatus.SC_OK) {
                byte[] tmp = new byte[4096];
                int bytesRead = 0;
                ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
                while ((bytesRead = in.read(tmp)) != -1) {
                    buffer.write(tmp, 0, bytesRead);
                }
                responseBody = buffer.toByteArray();
            }else{
                System.err.println("Method failed: " + postMethod.getStatusLine());
            }
            responseString =new String(responseBody,"UTF-8");
            responseBody=null;
        } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查请求地址!");
            e.printStackTrace();
        } catch (IOException e) { //发生网络异常
            System.out.println("网络连接异常!");
            e.printStackTrace();
        } finally {
            //释放连接
            postMethod.releaseConnection();
        }
        return responseString;
    }
    
    public static void main(String[] args) {
        Map<String,String> param = new HashMap<String,String>();
        param.put("userCode", "xxx");
        param.put("password", "xxx");
        login(url,param);
        System.out.println(get(testURL,param));
        //login(url,param);
    }
    
    public static String getCookieString() {
        return cookieString;
    }

    public static Cookie getCookie() {
        return cookie;
    }
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值