httpclient

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
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.entity.ContentType;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <b>Http工具</b><br>
 * 
 * @author     hunk
 * @date     2018年4月16日
 * @Copyright 
 *
 * <pre>
 * =================Modify Record=================
 * Modifier            date                Content
 * hunk                2018年4月16日             新增
 *
 * </pre>
 */
public class ClientHttpUtils {
    public static String CUST_PAY_INFO_PUSH_URL = "";
    
    public static String sendPOST(String POST_URL, Map<String, String> urlParam, String body) {
        //日誌
        CloseableHttpResponse response = null;
        try {
            RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000)
                    .setConnectionRequestTimeout(6000).build();
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            // HttpPost httpPost = new HttpPost(POST_URL);
            StringBuilder param = new StringBuilder("");
            // 將要拼接的參數urlencode
            for (String key : urlParam.keySet()) {
                param.append(key + "=" + URLEncoder.encode(urlParam.get(key), "UTF-8") + "&");
            }
            // pingjie
            HttpPost httpPost = new HttpPost(POST_URL + param.toString());
            // 請求參數設置
            if (StringUtils.isNotEmpty(body)) {
                StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // logger.error(e.getMessage(), e);
        } catch (ClientProtocolException e) {
            // logger.error(e.getMessage(), e);
        } catch (IOException e) {
            // logger.error(e.getMessage(), e);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    // logger.error(e.getMessage(), e);
                }
            }

        }

        return null;

    }
    
    public static byte[] sendPost(String url,Map<String,String> map) throws UnsupportedEncodingException{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> requestParams = new ArrayList<NameValuePair>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            requestParams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }

        HttpEntity reqEntity = new UrlEncodedFormEntity(requestParams,"utf-8");

        RequestConfig config = RequestConfig.custom().setConnectTimeout(20000)
                .setSocketTimeout(20000).setConnectionRequestTimeout(20000)
                .build();

        HttpPost post = new HttpPost(url);
        post.setEntity(reqEntity);
        post.setConfig(config);
        
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
//            logger().info(response);
            if(response.getStatusLine().getStatusCode() == 200){
//                logger().info("服務端響應成功,200,OK!");
                HttpEntity resEntity = response.getEntity();
                byte[] resultByte = EntityUtils.toByteArray(resEntity);
            //    String message = EntityUtils.toString(resEntity,"utf-8");
                return resultByte;
            }else{
//                logger().error("服務端返回異常,響應碼:"+response.getStatusLine().getStatusCode());
                return null;
            }

        } catch (IOException e) {
//            logger().error(e.getMessage(), e);
            e.printStackTrace();
//            logger().error("IO異常:"+e.getMessage());
            return null;
        }finally{
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static String sendJsonPost(String url,String json) throws UnsupportedEncodingException{
        CloseableHttpClient httpClient = HttpClients.createDefault();
       // List<NameValuePair> requestParams = new ArrayList<NameValuePair>();

       /* for (Map.Entry<String, String> entry : map.entrySet()) {
            requestParams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }*/

       // HttpEntity reqEntity = new UrlEncodedFormEntity(requestParams,"utf-8");
        StringEntity reqEntity = new StringEntity(json, Charset.forName("UTF-8"));
        reqEntity.setContentType("text/json");

        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000)
                .setSocketTimeout(60000).setConnectionRequestTimeout(60000)
                .build();
        

        HttpPost post = new HttpPost(url);
        post.setEntity(reqEntity);
        post.setConfig(config);
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
       
        
        
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            
            if(response.getStatusLine().getStatusCode() == 200){
//                logger().info("服務端響應成功,200,OK!");
                HttpEntity resEntity = response.getEntity();
            //    byte[] resultByte = EntityUtils.toByteArray(resEntity);
                String message = EntityUtils.toString(resEntity,"utf-8");
                return message;
            }else{
//                logger().error("服務端返回異常,響應碼:"+response.getStatusLine().getStatusCode());
                return null;
            }

        } catch (IOException e) {
//            logger().error(e.getMessage(), e);
            e.printStackTrace();
//            logger().error("IO異常:"+e.getMessage());
            return null;
        }finally{
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static String sendJsonPostForYcej(String json) throws UnsupportedEncodingException{
        return sendJsonPost(CUST_PAY_INFO_PUSH_URL,json);
    }

}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息