java利用httpclient通过get、post方式调用https接口

通过httpclient的get post方式调用http很常见。一般都是

HttpClient client = new DefaultHttpClient();  
HttpPost post = new HttpPost("http://127.0.0.1/login");

但是如果要调用https这个方式就不行了。就要修改DefaultHttpClient

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

先导入包

然后重写DefaultHttpClient的类

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

这时候就可以使用https方式调用了

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

    public static String doGet(String url,String charset) throws Exception{
        HttpClient httpClient = null;
        HttpGet Httpget = null;
        String result = null;

            httpClient = new SSLClient();
            Httpget = new HttpGet(url);
            Httpget.addHeader("Content-Type", "application/json");
            HttpGet.setEntity(se);
            HttpResponse response = httpClient.execute(Httpget);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }

        return result;
    }
    public static String doPost(String url,String json,String charset) throws Exception{
        HttpClient httpClient = null;
        HttpPost HttpPost = null;
        String result = null;

            httpClient = new SSLClient();
            HttpPost = new HttpPost(url);
            HttpPost.addHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(json);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            HttpPost.setEntity(se);
            HttpResponse response = httpClient.execute(HttpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }

        return result;
    }	
}

post调用代码

public static void main(String[] args) throws Exception{ 
        String url = "https://127.0.0.1/getuser";
        String json = "{\"id\":1}";
        String str = HttpClientUtil.doPost(url, json, "utf-8");
        System.out.println(str);
    }

get调用代码

public static void main(String[] args) throws Exception{ 
        String url = "https://127.0.0.1/getuser?id=1";
        String str = HttpClientUtil.doPost(url, "utf-8");
        System.out.println(str);
    }

StringEntity参数说明
se.setContentEncoding(new BasicHeader(“Content-Type”, “application/json”));
使用的是json模式 所以传的格式是json

application/xhtml+xml :XHTML格式
application/xml : XML数据格式
application/atom+xml :Atom XML聚合格式
application/json : JSON数据格式
application/pdf :pdf格式
application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded : 中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

HttpPost.addHeader("Content-Type", " application/x-www-form-urlencoded");
List<NameValuePair> params=new ArrayList<>();
params.add(new BasicNameValuePair("key1","value1"));
params.add(new BasicNameValuePair("key2","value2"));
params.add(new BasicNameValuePair("key3","value3"));
UrlEncodedFormEntity  entity=new UrlEncodedFormEntity(params,"UTF-8");
HttpPost.setEntity(entity);

如果要采用表单提交方式就需要修改成上面所描述的方式。

Java中可以使用Apache HttpClient库来发送HTTP请求,包括GET、POST方式,也可以通过HttpClient库发送HTTPS请求。使用HttpClient发送HTTPS请求需要添加SSL证书和设置SSL连接的相关参数。 以下是通过HttpClient库发送GET、POST请求的示例代码: 1. 发送GET请求 ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 2. 发送POST请求 ```java import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api"; HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); String requestBody = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 如果需要发送HTTPS请求,则需要添加SSL证书和设置SSL连接的相关参数。具体可以参考以下示例代码: ```java import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpClientTest { public static void main(String[] args) throws Exception { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslSocketFactory) .register("http", new PlainConnectionSocketFactory()) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); String url = "https://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 需要注意的是,以上代码中的SSL证书验证方式为信任所有证书,不建议在生产环境中使用。建议根据实际情况设置合适的证书验证方式
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值