httpclient 使用

http请求

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;  

private String findFromRemote(Date date){
        int socketTimeout = 10*1000;
        int connectTimeout = 10*1000;  
        String result = "";        
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        try {
            HttpPost httpPost = new HttpPost(REMOTE_SERVER_URL);
            // 设置请求器的配置
            httpPost.setConfig(requestConfig);
            List<NameValuePair> pair = new ArrayList<NameValuePair>(2);
            pair.add(new BasicNameValuePair("date", "2017-3-22"));
            pair.add(new BasicNameValuePair("key","0ad9fcd5282912bc8b7b5655a3718e78"));
            httpPost.setEntity(new UrlEncodedFormEntity(pair, "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            } 
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
        return result;
}

https 请求:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

//method
 
String result = ""; 
        final String url = "https://v.juhe.cn/calendar/day?date=2015-1-1&key=0ad9fcd5282912bc8b7b5655a3718e78";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (url.startsWith("https")) {
                // https访问
                httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
            } else {
                // 普通的http调用
                httpClient = HttpClients.createDefault();
            }
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//            nvps.add(new BasicNameValuePair("mobile", "1111222"));
//            nvps.add(new BasicNameValuePair("md5Password", "md5加密的密文"));
//            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            try {
                response = httpClient.execute(httpPost);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                } 
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

证书加载

/**
     * 初始化证书
     * 
     * @param certLocalPath
     *            证书地址
     * @param certPassword
     *            证书密码
     * @param socketTimeout
     * @param connectTimeout
     */
    private static void initSsl(String certLocalPath, String certPassword, CloseableHttpClient httpClient,
            String responseStr) {
        try {
            // 获得密匙库
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File(certLocalPath));// 加载本地的证书进行https加密传输
            try {
                keyStore.load(instream, certPassword.toCharArray());// 设置证书密码
            } catch (CertificateException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } finally {
                instream.close();
            }

            // Trust own CA and all self-signed certs
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                    null, new DefaultHostnameVerifier());

            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"KeyManagementException\"}";
        } catch (UnrecoverableKeyException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"UnrecoverableKeyException\"}";
        } catch (KeyStoreException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"KeyStoreException\"}";
        } catch (FileNotFoundException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"FileNotFoundException\"}";
        } catch (NoSuchAlgorithmException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"NoSuchAlgorithmException\"}";
        } catch (ClientProtocolException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"ClientProtocolException\"}";
        } catch (IllegalStateException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"IllegalStateException\"}";
        } catch (IOException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"IOException\"}";
        }
    }

    /**
     * 建立post请求
     * 
     * @param url
     * @param nameValuePair
     * @param timeoutConnection
     *            设置连接超时时间(毫秒)
     * @param timeoutSocket
     *            设置默认的套接字超时(so_timeout毫秒)。这是为了等待数据超时。
     * @param charset
     *            编码类型
     * @param certLocalPath
     *            证书地址
     * @param certPassword
     *            证书密码
     * @param isNeedSssl
     *            是否需要证书
     * @return String 请求返回结果
     */
    public static String buildPostRequest(String url, Map<String, String> nameValuePair, int timeoutConnection,
            int timeoutSocket, String charset, String certLocalPath, String certPassword, boolean isNeedSssl) {
        String responseStr = "";
        // 获得httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (isNeedSssl) {
                initSsl(certLocalPath, certPassword, httpClient, responseStr);
            }
            // 根据默认超时限制初始化requestConfig
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutSocket)
                    .setConnectTimeout(timeoutConnection).build();

            HttpPost httpPost = new HttpPost(url);
            UrlEncodedFormEntity entity = null;
            // 设置httpPost请求参数
            if (null != charset
                    && (charset.compareToIgnoreCase("GBK") == 0 || charset.compareToIgnoreCase("GB3212") == 0)) {
                entity = new UrlEncodedFormEntity(generatNamePair(nameValuePair), "GBK");
            } else {
                entity = new UrlEncodedFormEntity(generatNamePair(nameValuePair), "UTF-8");
            }
            entity.setContentEncoding(charset);
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(entity);
            // 设置请求器的配置
            httpPost.setConfig(requestConfig);
            // 使用execute方法发送HTTP Post请求,并返回HttpResponse对象
            HttpResponse httpResponse = httpClient.execute(httpPost);

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                responseStr = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            } else {
                responseStr = "{\"error_response\":\"request failed\"}";
            }
        } catch (ClientProtocolException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"ClientProtocolException\"}";
        } catch (IllegalStateException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"IllegalStateException\"}";
        } catch (IOException e) {
            responseStr = "{\"is_success\":\"F\",\"error_code\":\"IOException\"}";
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
               
            }
        }
        return responseStr;
    }

cookies 获取

 public void doPost(String url, Map<String, String> param, Map<String, String> requestHeader, List<Cookie> cookies) throws IOException {
        DBHttpClientResponse _response = null;

        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.config);
        //添加参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (param != null && param.size() != 0) {
            for (String key : param.keySet()) {
                nvps.add(new BasicNameValuePair(key, param.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        }


        //设置请求头
        if (requestHeader == null) {
            requestHeader = HEADMAP;
        }
        for (String str : requestHeader.keySet()) {
            httpPost.setHeader(str, requestHeader.get(str));
        }

        //添加cookieStore 请求完后,就可以从这个变量中获取cookie
        CookieStore cookieStore = new BasicCookieStore();
       
        //创建httpclient
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse response;

        response = client.execute(httpPost);
       
        List<Cookie> cookies = cookieStore.getCookies(); //得到的cookies
        

        response.close();
        client.close();
       
    }

添加cookies

 public void doPost(String url, Map<String, String> param, Map<String, String> requestHeader, List<Cookie> cookies) throws IOException {
        DBHttpClientResponse _response = null;

        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.config);
        //添加参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (param != null && param.size() != 0) {
            for (String key : param.keySet()) {
                nvps.add(new BasicNameValuePair(key, param.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        }


        //设置请求头
        if (requestHeader == null) {
            requestHeader = HEADMAP;
        }
        for (String str : requestHeader.keySet()) {
            httpPost.setHeader(str, requestHeader.get(str));
        }
        //添加cookie
        if (cookies != null && cookies.size() != 0) {
            StringBuilder cookiesBuilder = new StringBuilder();
            for (String str : cookies.keySet()) {
                cookiesBuilder.append(str + "=" + cookies.get(str) + ";");
            }
            cookiesBuilder.deleteCharAt(cookiesBuilder.length() - 1);
            httpPost.setHeader("Cookie", cookiesBuilder.toString());
        }
        //添加cookieStore 请求完后,就可以从这个变量中获取cookie
        CookieStore cookieStore = new BasicCookieStore();
      
        //创建httpclient
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse response;

        response = client.execute(httpPost);
       
List<Cookie> cookies = cookieStore.getCookies(); //得到的cookies
        

        response.close();
        client.close();
       
    }

 

转载于:https://my.oschina.net/u/2552286/blog/864760

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值