Java发送HTTP或者HTTPS请求

简介: Java发送HTTP或者HTTPS请求
+关注继续查看

气死我了,整个CSDN我连个像样的HTTPClient都找不到,有的居然还要收费,干脆自己发布一个,供大家参考!!!


代码如下

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * http请求客户端
 * @author Administrator
 */
public class HttpClient {
    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;

    public boolean isHttps() {
        return isHttps;
    }

    public void setHttps(boolean isHttps) {
        this.isHttps = isHttps;
    }

    public String getXmlParam() {
        return xmlParam;
    }

    public void setXmlParam(String xmlParam) {
        this.xmlParam = xmlParam;
    }

    public HttpClient(String url, Map<String, String> param) {
        this.url = url;
        this.param = param;
    }

    public HttpClient(String url) {
        this.url = url;
    }

    public void setParameter(Map<String, String> map) {
        param = map;
    }

    public void addParameter(String key, String value) {
        if (param == null)
            param = new HashMap<String, String>();
        param.put(key, value);
    }

    public void post() throws ClientProtocolException, IOException {
        HttpPost http = new HttpPost(url);
        setEntity(http);
        execute(http);
    }

    public void put() throws ClientProtocolException, IOException {
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    }

    public void get() throws ClientProtocolException, IOException {
        if (param != null) {
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) {
                if (isFirst)
                    url.append("?");
                else
                    url.append("&");
                url.append(key).append("=").append(param.get(key));
            }
            this.url = url.toString();
        }
        HttpGet http = new HttpGet(url);
        execute(http);
    }

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
        if (param != null) {
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            for (String key : param.keySet())
                nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
        }
        if (xmlParam != null) {
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        }
    }

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException {
        CloseableHttpClient httpClient = null;
        try {
            if (isHttps) {
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
                            // 信任所有
                            public boolean isTrusted(X509Certificate[] chain,
                                    String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            CloseableHttpResponse response = httpClient.execute(http);
            try {
                if (response != null) {
                    if (response.getStatusLine() != null)
                        statusCode = response.getStatusLine().getStatusCode();
                    HttpEntity entity = response.getEntity();
                    // 响应内容
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getContent() throws ParseException, IOException {
        return content;
    }

}

要导入的pom.xml依赖就一个:

<!--httpclient依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
相关文章
|
14天前
|
域名解析 负载均衡 JavaScript
升级 HTTP 至 HTTPS:使用 Nginx 反向代理
升级 HTTP 至 HTTPS:使用 Nginx 反向代理
21 0
|
19天前
|
网络协议 算法 安全
Android 面试必备 - 计算机网络基本知识(TCP,UDP,Http,https)
Android 面试必备 - 计算机网络基本知识(TCP,UDP,Http,https)
|
2月前
|
应用服务中间件 Linux 网络安全
【WEB】当HTTPS资源引入HTTP导致报错blocked:mixed-content (混合加载/Mixed Content)如何解决
【WEB】当HTTPS资源引入HTTP导致报错blocked:mixed-content (混合加载/Mixed Content)如何解决
【WEB】当HTTPS资源引入HTTP导致报错blocked:mixed-content (混合加载/Mixed Content)如何解决
|
2月前
|
网络协议 安全 网络安全
http和https的区别?
HTTP协议是基于传输层的TCP协议进行通信,通用无状态的协议。80端口
|
2月前
|
网络协议 安全 算法
【网站建设】HTTP/HTTPS 是什么?有什么区别?
【网站建设】HTTP/HTTPS 是什么?有什么区别?
36 0
|
2月前
|
安全 网络安全 数据安全/隐私保护
Http和Https区别
Http和Https区别
|
2月前
|
存储 网络协议 安全
半小时搞懂 HTTP、HTTPS和HTTP2(下)
半小时搞懂 HTTP、HTTPS和HTTP2(下)
49 0
|
2月前
|
缓存 算法 网络协议
半小时搞懂 HTTP、HTTPS和HTTP2(中)
半小时搞懂 HTTP、HTTPS和HTTP2(中)
29 0
|
2月前
|
Web App开发 存储 缓存
半小时搞懂 HTTP、HTTPS和HTTP2(上)
半小时搞懂 HTTP、HTTPS和HTTP2
35 0
|
2月前
|
存储 缓存 前端开发
【计算机网络】HTTP/HTTPS协议基础知识汇总
【计算机网络】HTTP/HTTPS协议基础知识汇总
175 1
相关产品
云迁移中心
推荐文章
更多