Java 请求https 的各种方式详细代码

开始前的准备:

需要https://XXXXX下的访问证书保存为cer文件。


基础代码:

1、参考两篇文章:

http://blog.csdn.net/liuxiaoshuang002/article/details/51955020  用来判断是否为空

http://blog.csdn.net/liuxiaoshuang002/article/details/51955031  比较对象是否相等

2、请求后返回的实体  HttpResponseEntity   详细代码如下:


package com.gj5u.publics.util.httpweb;

import java.util.Map;
/**
 * 获取内容实体
 * @author Rex
 *
 */
public class HttpResponseEntity
{
    private Map<String,String> resHeaders;
    private String httpBody;
    private String statusLine;
    private String ErrMessage;
    /**
     * Header信息
     * @return Header信息
     */
    public Map<String, String> getResHeaders()
    {
        return resHeaders;
    }
    /**
     * Header信息
     * @param resHeaders Header信息
     */
    public void setResHeaders(Map<String, String> resHeaders)
    {
        this.resHeaders = resHeaders;
    }
    /**
     *  Body 内容
     * @return Body 内容
     */
    public String getHttpBody()
    {
        return httpBody;
    }
    /**
     *  Body 内容
     * @param httpBody Body 内容
     */
    public void setHttpBody(String httpBody)
    {
        this.httpBody = httpBody;
    }
    /**
     * 状态行
     * @return 状态行
     */
    public String getStatusLine()
    {
        return statusLine;
    }
    /**
     * 状态行
     * @param statusLine 状态行
     */
    public void setStatusLine(String statusLine)
    {
        this.statusLine = statusLine;
    }
    public String getErrMessage()
    {
        return ErrMessage;
    }
    public void setErrMessage(String errMessage)
    {
        ErrMessage = errMessage;
    }
    
}




关于请求的详细代码


package com.gj5u.publics.util.httpweb;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import cn.ava.publics.util.EmptyUtil;
import cn.ava.publics.util.EqualsUtil;

public class MyHttpsConn
{
    // [start] 属性定义
    /*
     * 请求的URL
     */
    private String Requrl;
    private String WebCerPath;
    private Map<String, String> ReqHeaderKV;
    
    /**
     * Http请求方式
     * 
     * @author Rex
     *
     */
    public enum HttpMethod
    {
        POST, GET, DELETE, HEAD, PATCH, TRACE, OPTIONS, PUT
    }
    
    public String getRequrl()
    {
        return Requrl;
    }
    
    public String getWebCerPath()
    {
        return WebCerPath;
    }
    
    public Map<String, String> getReqHeaderKV()
    {
        return ReqHeaderKV;
    }
    
    // [end]
    /**
     * 初始化
     * 
     * @param url
     *            请求URL
     * @param cerpath
     *            证书路径
     * @param cerpwd
     *            证书密码
     */
    public MyHttpsConn(String url, String cerpath)
    {
        Requrl = url;
        WebCerPath = cerpath;
    }
    
    public HttpResponseEntity SendHttps(HttpMethod Method, Map<String, String> Parameters, Map<String, String> Header, String Body, String[] HeaderField)
    {
        HttpPost httpPost = new HttpPost(Requrl);
        HttpGet httpGet = new HttpGet(Requrl);
        HttpDelete httpDelete = new HttpDelete(Requrl);
        HttpHead httpHead = new HttpHead(Requrl);
        HttpPatch httpPatch = new HttpPatch(Requrl);
        HttpTrace httpTrace = new HttpTrace(Requrl);
        HttpOptions httpOptions = new HttpOptions(Requrl);
        HttpPut httpPut = new HttpPut(Requrl);
        // 1、将URL参数写入URL中
        if (EmptyUtil.isNotEmpty(Parameters))
        {
            String pvalue = "";
            for (Map.Entry<String, String> entry : Parameters.entrySet())
            {
                if (pvalue != "")
                {
                    pvalue += "&";
                }
                pvalue += entry.getKey() + "=" + entry.getValue();
            }
            if (pvalue != "")
            {
                this.Requrl += "?" + pvalue;
            }
        }
        // 2、将header写入header中
        if (EmptyUtil.isNotEmpty(Header))
        {
            for (Map.Entry<String, String> entry : Header.entrySet())
            {
                if (EqualsUtil.ObjEquals(HttpMethod.POST, Method))
                {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.GET, Method))
                {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.DELETE, Method))
                {
                    httpDelete.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.HEAD, Method))
                {
                    httpHead.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.OPTIONS, Method))
                {
                    httpOptions.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method))
                {
                    httpPatch.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method))
                {
                    httpPut.setHeader(entry.getKey(), entry.getValue());
                }
                else if (EqualsUtil.ObjEquals(HttpMethod.TRACE, Method))
                {
                    httpTrace.setHeader(entry.getKey(), entry.getValue());
                }
            }
        }
        // 3、 请求消息体设置
        HttpEntity entity = new StringEntity(Body, "UTF-8");
        if (EqualsUtil.ObjEquals(HttpMethod.POST, Method))
        {
            httpPost.setEntity(entity);
        }
        else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method))
        {
            httpPatch.setEntity(entity);
        }
        else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method))
        {
            httpPut.setEntity(entity);
        }
        SSLSocketFactoryLoad.loadSSLSocketFactory(this.WebCerPath);
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        Boolean isHttps = this.Requrl.startsWith("https");
        CloseableHttpClient httpclient = HttpClientConstructor.getHttpClient(isHttps);
        if (isHttps)
        {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// 设置请求和传输超时时间
            if (EqualsUtil.ObjEquals(HttpMethod.POST, Method))
            {
                httpPost.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.GET, Method))
            {
                httpGet.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.DELETE, Method))
            {
                httpDelete.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.HEAD, Method))
            {
                httpHead.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.OPTIONS, Method))
            {
                httpOptions.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method))
            {
                httpPatch.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method))
            {
                httpPut.setConfig(requestConfig);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.TRACE, Method))
            {
                httpTrace.setConfig(requestConfig);
            }
        }
        CloseableHttpResponse responseBody = null;
        try
        {
            if (EqualsUtil.ObjEquals(HttpMethod.POST, Method))
            {
                responseBody = httpclient.execute(httpPost);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.GET, Method))
            {
                responseBody = httpclient.execute(httpGet);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.DELETE, Method))
            {
                responseBody = httpclient.execute(httpDelete);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.HEAD, Method))
            {
                responseBody = httpclient.execute(httpHead);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.OPTIONS, Method))
            {
                responseBody = httpclient.execute(httpOptions);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method))
            {
                responseBody = httpclient.execute(httpPatch);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method))
            {
                responseBody = httpclient.execute(httpPut);
            }
            else if (EqualsUtil.ObjEquals(HttpMethod.TRACE, Method))
            {
                responseBody = httpclient.execute(httpTrace);
            }
            responseEntity = dealWithResponse(responseBody);
            ReqHeaderKV = new HashMap<String, String>();
            for (Map.Entry<String, String> entry : responseEntity.getResHeaders().entrySet())
            {
                if (EmptyUtil.isNotEmpty(HeaderField))
                {
                    for (int i = 0; i < HeaderField.length; i++)
                    {
                        if (EqualsUtil.StringEquals(entry.getKey(), HeaderField[i], false))
                        {
                            ReqHeaderKV.put(entry.getKey(), entry.getValue());
                        }
                    }
                }
                else
                {
                    ReqHeaderKV.put(entry.getKey(), entry.getValue());
                }
            }
        }
        catch (Exception e)
        {
            responseEntity.setErrMessage("Send request failed.\n" + e.getMessage());
            e.printStackTrace();
        }
        finally
        {
            try
            {
                httpclient.close();
            }
            catch (Exception e)
            {
                responseEntity.setErrMessage("httpclient closed failed.\n" + e.getMessage());
            }
        }
        return responseEntity;
    }
    
    private HttpResponseEntity dealWithResponse(CloseableHttpResponse responseBody)
    {
        BufferedReader reader = null;
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try
        {
            Header[] resHeaders = responseBody.getAllHeaders();
            Map<String, String> resHeadersArray = new HashMap<String, String>();
            for (int i = 0; i < resHeaders.length; i++)
            {
                resHeadersArray.put(resHeaders[i].getName(), resHeaders[i].getValue());
            }
            responseEntity.setResHeaders(resHeadersArray);
            responseEntity.setStatusLine(new String(responseBody.getStatusLine().toString().getBytes("ISO-8859-1"), "UTF-8"));
            InputStream content = responseBody.getEntity().getContent();
            reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
            String line = null;
            StringBuilder strBuffer = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                strBuffer.append(line + "\n");
            }
            responseEntity.setHttpBody(strBuffer.toString());
        }
        catch (Exception e)
        {
            responseEntity.setErrMessage("Failed to analysing http response.\n" + e.getMessage());
        }
        finally
        {
            try
            {
                reader.close();
            }
            catch (Exception e)
            {
                responseEntity.setErrMessage("reader close error .\n" + e.getMessage());
            }
        }
        return responseEntity;
    }
}


使用方法

  MyHttpsConn httpconn = new MyHttpsConn(httpsurl, CerPath);   //请求的URL和证书路径
        HttpResponseEntity httpentry = httpconn.SendHttps(HttpMethod.GET, Parameters, ReqHeader, Body,GetHeader);
       


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值