自己写的java模拟请求帮助类,已经包含header头构造,会话session维持

package com.haozl.back.util;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

    private String TextEncoding = "gb2312";
    private String ResultEncoding="utf-8";//返回的网页结果编码
    private Map<String, String> headers;
    private String SessionId;
    private boolean SessionIdFlag;//首次是否需要获取Sessionid

    public HttpClientUtil(){
    }

    public HttpClientUtil(Map<String, String> headers){
        this.headers=headers;
    }

    /**
     * 会话维持
     * @param headers
     * @param sessionId
     */
    public HttpClientUtil(Map<String, String> headers, String sessionId) {
        this.headers = headers;
        this.SessionId = sessionId;
        this.headers.put("Cookie", this.SessionId);
        this.SessionIdFlag=false;//第二次请求不需要记录SessionId
    }

    /**
     * 发送post请求
     * 异常或者没拿到返回结果的情况下,result为""
     */
    public String httpPost(String url, Map<String, String> param) {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity entity = null;
        String result = "";
        StringBuffer sb = new StringBuffer();
        try {
            httpclient = new DefaultHttpClient();
            //设置cookie的兼容性---考虑是否需要
            httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
            httpPost = new HttpPost(url);
            //设置各种头信息
            ) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //传入各种参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (param != null) {
                String key=null, value=null;
                for (Entry<String, String> set : param.entrySet()) {
                    key = set.getKey();
                    value = set.getValue() == null ? "" : set.getValue();
                    nvps.add(new BasicNameValuePair(key, value));
                    sb.append(" [" + key + "-" + value + "] ");
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, this.TextEncoding));
            //设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), );
            //设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpPost.getParams(), );
            //开始进行请求
            response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {//请求不成功
                System.out.println("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
                return "error";
            }
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, this.TextEncoding);
            } else {
                result = "";
            }
            if(this.SessionIdFlag==true){
                //获取SessionId
                String cookieValue=response.getFirstHeader("Set-Cookie").getValue();
                , cookieValue.indexOf(";"));
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return result;
    }

    /**
     * 发送post请求
     * 异常或者没拿到返回结果的情况下,result为""
     */
    public String httpPost2(String url, Map<String, String[]> param) {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity entity = null;
        String result = "";
        StringBuffer sb = new StringBuffer();
        try {
            httpclient = new DefaultHttpClient();
            //设置cookie的兼容性---考虑是否需要
            httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
            httpPost = new HttpPost(url);
            //设置各种头信息
            ) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //传入各种参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (param != null) {
                String key=null;
                for (Entry<String, String[]> set : param.entrySet()) {
                    key = set.getKey();
                    if(set.getValue()==null){
                        nvps.add(new BasicNameValuePair(key, ""));
                        sb.append(" [" + key + "-" + "" + "] ");
                    }else{
                        for(String val : set.getValue()){
                            val=val==null ? "" : val;
                            nvps.add(new BasicNameValuePair(key, val));
                            sb.append(" [" + key + "-" + val + "] ");
                        }
                    }
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, this.TextEncoding));
            //设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), );
            //设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpPost.getParams(), );
            //开始进行请求
            response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {//请求不成功
                System.out.println("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
                return "error";
            }
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, this.TextEncoding);
            } else {
                result = "";
            }
            if(this.SessionIdFlag==true){
                //获取SessionId
                String cookieValue=response.getFirstHeader("Set-Cookie").getValue();
                , cookieValue.indexOf(";"));
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return result;
    }

    /**
     * 发送post请求
     * 异常或者没拿到返回结果的情况下,result为""
     */
    public String httpPost3(String url, String  param) {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity entity = null;
        String result = "";
        //StringBuffer sb = new StringBuffer();
        try {
            httpclient = new DefaultHttpClient();
            //设置cookie的兼容性---考虑是否需要
            httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
            httpPost = new HttpPost(url);
            //设置各种头信息
            ) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //传入各种参数
/*            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (param != null) {
                for (Entry<String, String[]> set : param.entrySet()) {
                    String key = set.getKey();
                    if(set.getValue()==null){
                        nvps.add(new BasicNameValuePair(key, ""));
                        sb.append(" [" + key + "-" + "" + "] ");
                    }else{
                        for(String val : set.getValue()){
                            val=val==null ? "" : val;
                            nvps.add(new BasicNameValuePair(key, val));
                            sb.append(" [" + key + "-" + val + "] ");
                        }
                    }
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, this.TextEncoding));
            */
              // 构造最简单的字符串数据
            StringEntity reqeustEntity = new StringEntity(param,this.TextEncoding);
            // 设置类型
            //reqEntity.setContentType("application/x-www-form-urlencoded");
            // 设置请求的数据
            httpPost.setEntity(reqeustEntity);
            //设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), );
            //设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpPost.getParams(), );
            //开始进行请求
            response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {//请求不成功
                System.out.println("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
                return "error";
            }
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, this.TextEncoding);
            } else {
                result = "";
            }
            if(this.SessionIdFlag==true){
                //获取SessionId
                String cookieValue=response.getFirstHeader("Set-Cookie").getValue();
                , cookieValue.indexOf(";"));
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return result;
    }

    /**
     * 文件上传请求
     */
    public String httpPostFile(String url, Map<String, String> param, File file) {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity entity = null;
        String result = "";
        //StringBuffer sb = new StringBuffer();
        try {
            httpclient = new DefaultHttpClient();
            //设置cookie的兼容性---考虑是否需要
            httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
            //httpclient.getParams().setParameter("http.protocol.content-charset",Charset.forName(this.TextEncoding));
            httpPost = new HttpPost(url);
            //设置各种头信息
            ) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            FileBody fileBody=new FileBody(file);
            //对请求的表单域进行填充
            //MultipartEntity reqeustEntity = new MultipartEntity();
            MultipartEntity reqeustEntity =new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(this.TextEncoding));
            if(param!=null){
                String key=null,value=null;
                StringBody body;
                for (Entry<String, String> set : param.entrySet()) {
                    key = set.getKey();
                    value=set.getValue()==null ? "" : set.getValue();
                    body=new StringBody(value,Charset.forName(this.TextEncoding));
                    reqeustEntity.addPart(key, body);
                }
            }
            reqeustEntity.addPart("file1", fileBody);//本案例中file1在后
            // 设置类型
            //reqeustEntity.setContentType("application/x-www-form-urlencoded");
            // 设置请求的数据
            httpPost.setEntity(reqeustEntity);
            //设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), );
            //设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpPost.getParams(), );
            System.out.println("executing request " + httpclient.getRequestExecutor());
            //开始进行请求
            response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {//请求不成功
                System.out.println("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
                return "error";
            }
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, this.TextEncoding);
            } else {
                result = "";
            }
            if(this.SessionIdFlag==true){
                //获取SessionId
                String cookieValue=response.getFirstHeader("Set-Cookie").getValue();
                , cookieValue.indexOf(";"));
            }
        }catch(Exception e){
            e.toString();
        }
        return result;
    }

    /**
     * 发送 get 请求
     * param转换为url地址中的&
     */
    public String httpGet(String url, Map<String, String> param, boolean flagUrlAdd) {
        String result = null;
        DefaultHttpClient httpclient = null;
        HttpGet httpGet = null;
        HttpResponse response=null;
        StringBuffer sb=new StringBuffer();
        try {
            //传入参数
            ){
                sb.append(flagUrlAdd==true ? "&" : "");//类似这种http://www.baidu.com/cgi-bin/Info.dll?haozhulin&password=123456
                Iterator<Entry<String,String>> it=param.entrySet().iterator();
                Entry<String,String> entry=null;
                String value=null;
                while(it.hasNext()){
                    entry=it.next();
                    value= param.get(entry.getKey())==null ? "" : entry.getValue();
                    sb.append(entry.getKey()).append("=").append(value);
                    if(it.hasNext()){
                        sb.append("&");
                    }
                }
            }
            httpclient=new DefaultHttpClient();
            System.out.println(url+sb.toString());
            httpGet=new HttpGet(url+sb.toString());
            //设置各种头信息
            ) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, this.TextEncoding);
            if(this.SessionIdFlag==true){
                //获取SessionId
                String cookieValue=response.getFirstHeader("Set-Cookie").getValue();
                , cookieValue.indexOf(";"));
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        return result;
    }

    public String getTextEncoding() {
        return TextEncoding;
    }

    public void setTextEncoding(String textEncoding) {
        TextEncoding = textEncoding;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public String getSessionId() {
        return SessionId;
    }

    public void setSessionId(String sessionId) {
        SessionId = sessionId;
    }

    public boolean getSessionIdFlag() {
        return SessionIdFlag;
    }

    public void setSessionIdFlag(boolean sessionIdFlag) {
        SessionIdFlag = sessionIdFlag;
    }

    public String getResultEncoding() {
        return ResultEncoding;
    }

    public void setResultEncoding(String resultEncoding) {
        ResultEncoding = resultEncoding;
    }

}
  

java HttpClientUtil帮助类的更多相关文章

  1. java自定义注解类

    一.前言 今天阅读帆哥代码的时候,看到了之前没有见过的新东西, 比如java自定义注解类,如何获取注解,如何反射内部类,this$0是什么意思? 于是乎,学习并整理了一下. 二.代码示例 import ...

  2. 基础知识(05) -- Java中的类

    Java中的类 1.类的概念 2.类中的封装 3.对象的三大特征 4.对象状态 5.类与类之间的关系 ------------------------------------------------- ...

  3. java中Inetaddress类

    InetAddress类 InetAddress类用来封装我们前面讨论的数字式的IP地址和该地址的域名. 你通过一个IP主机名与这个类发生作用,IP主机名比它的IP地址用起来更简便更容易理解. Ine ...

  4. Java集合---Array类源码解析

    Java集合---Array类源码解析              ---转自:牛奶.不加糖 一.Arrays.sort()数组排序 Java Arrays中提供了对所有类型的排序.其中主要分为Prim ...

  5. 浅析Java.lang.ProcessBuilder类

    最近由于工作需要把用户配置的Hive命令在Linux环境下执行,专门做了一个用户管理界面特地研究了这个不经常用得ProcessBuilder类.所以把自己的学习的资料总结一下. 一.概述      P ...

  6. 浅析Java.lang.Process类

    一.概述      Process类是一个抽象类(所有的方法均是抽象的),封装了一个进程(即一个执行程序).      Process 类提供了执行从进程输入.执行输出到进程.等待进程完成.检查进程的 ...

  7. 浅析Java.lang.Runtime类

    一.概述      Runtime类封装了运行时的环境.每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接.      一般不能实例化一个Runtime对象, ...

  8. java单例类/

    java单例类  一个类只能创建一个实例,那么这个类就是一个单例类 可以重写toString方法 输出想要输出的内容 可以重写equcal来比较想要比较的内容是否相等 对于final修饰的成员变量 一 ...

  9. JAVA中的类和接口

    1.类: 类是具有相同属性和方法的一组对象的集合,它为属于该类的所有对象提供了统一的抽象描述,其内部包括属性和方法两个主要部分.在面向对象的编程语言中,类是一个独立的程序单位,它应该有一个类名并包括属 ...

随机推荐

  1. 使用mysqldump对mysql进行备份与恢复

    说明: 主参考:https://blog.csdn.net/fanren224/article/details/79693860 mysql数据全量备份 1.开启二进制日志,备份指定数据库 cat & ...

  2. [计蒜客T2238]礼物_线段树_归并排序_概率期望

    礼物 题目大意: 数据范围: 题解: 这题有意思啊($md$卡常 直接做怎么做? 随便上个什么东西,维护一下矩阵乘和插入,比如说常数还算小的$KD-Tree$(反正我是没见人过过 我们漏掉了一个条件, ...

  3. iview给布局MenuItem标签绑定点击事件

    @click.native="menuHandleClick"

  4. Boot-crm管理系统开发教程(一)

    ps:上周就把这个项目写完了,一直忘记记录,现在补上. Boot-crm是书上第十八章的内容,书上提供了前端的代码,所以只需要写后端的代码就可以了,①所以我们先把前端的代码移植到项目中. ②然后在li ...

  5. 开始写下自己的python的cocos2d, pyglet学习

    开始写下自己的python的cocos2d, pyglet学习 2014年01月18日 13:52:36 我要做程序达人 阅读数 9051更多 分类专栏: python的cocos2d和pyglet ...

  6. 怎样理解Node对象接口

    dom中的节点都继承自Node接口, 也就是说, 所有的节点都具有Node接口所规定的属性和方法, 比如下面这个 <a> 标签, 它也继承了Node的所有属性和方法: 可以认为Node接口 ...

  7. mybatis 延迟加载学习

    一.什么是延迟加载 resultMap可实现高级映射(使用association.collection实现一对一及一对多映射),association.collection具备延迟加载功能. 需求: ...

  8. Stacey矩阵简介

    1. Stacey 矩阵包含哪几个区域? 1区:Simple 第一个区域,需求明确,技术(解决方案)也确定,这类项目就是简单的项目(Simple):比如注册一个新公司,需求很明确,手续也很清楚,就那么 ...

  9. 【zhifu】web开发中的支付宝支付和微信支付

    一.支付类型: 支付宝支付: 支付宝app内的网页支付: app外(即普通浏览器)网页支付: 微信支付: 微信app内的支付(在这里叫公众号支付) app外的支付(微信H5支付): 微信公众号的支付宝 ...

  10. 分库分布的几件小事(五)MYSQL读写分离

    1.为什么进行读写分离 这个,高并发这个阶段,那肯定是需要做读写分离的,啥意思?因为实际上大部分的互联网公司,一些网站,或者是app,其实都是读多写少.所以针对这个情况,就是写一个主库,但是主库挂多个 ...