欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpCilent 实例(2)  

程序员文章站 2024-02-09 22:09:46
...
封装的HttpCilent工具类


public class HttpRequestUtil {

    private static Logger log = LoggerFactory.getLogger(HttpRequestUtil.class);

    /**
     * 发送get请求
     * @param url
     * @param decodeCharset
     * @return
     */
    public static String sendGetRequest(String url, String decodeCharset) {
        HttpClient httpclient = new DefaultHttpClient();
        String responseContent = null;
        HttpGet httpGet = new HttpGet(url);
        HttpEntity entity = null;
        try {
            HttpResponse response = httpclient.execute(httpGet);
            System.out.println(response);
            entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
            }
        } catch (Exception e) {
            log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
        } finally {
            try {
                EntityUtils.consume(entity);
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ex) {
                log.error("net io excepiton", ex);
            }
        }
        return responseContent;
    }

    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static String sendGetRequest(String url) {
        return sendGetRequest(url, "UTF-8");
    }

    public static String sendHttpPostRequest(String reqURL, String data) {
        HttpClient httpclient = new DefaultHttpClient();
        String respStr = "";
        try {
            HttpPost httppost = new HttpPost(reqURL);
            StringEntity strEntity = new StringEntity(data, "UTF-8");
            strEntity.setContentType("application/x-www-form-urlencoded");
            httppost.setEntity(strEntity);
            log.info(EntityUtils.toString(strEntity));
            log.info("executing request " + httppost.getRequestLine());

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {
                log.info("返回数据长度: " + resEntity.getContentLength());
                respStr = EntityUtils.toString(resEntity);
                log.info("respStr " + respStr);
            }

        } catch (ClientProtocolException e) {
            log.error("sendHttpPostRequest : " ,e);
        } catch (IOException e) {
            log.error("sendHttpPostRequest : " ,e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return respStr;
    }

    /**
     * 发送post请求
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String sendHttpPostRequest(String url, Map<String, String> params) {
        String respStr = "";
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
        httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); 
        log.info("url: " + url);
        log.info("params: " + params);
        try {
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
            post.setEntity(entity);
            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                log.info("返回数据长度: " + resEntity.getContentLength());
                respStr = EntityUtils.toString(resEntity);
                log.info("respStr " + respStr);
            }
        } catch (ClientProtocolException e) {
            log.error("sendHttpPostRequest : " +e);
        } catch (IOException e) {
            log.error("sendHttpPostRequest : " +e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return respStr;
    }
    
    /**
     * 发送post请求
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String sendHttpPostRequestToObject(String url, Map<String, Object> params) {
        String respStr = "";
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
        httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); 
        log.info("url: " + url);
        log.info("params: " + params);
        try {
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
            post.setEntity(entity);
            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                log.info("返回数据长度: " + resEntity.getContentLength());
                respStr = EntityUtils.toString(resEntity);
                log.info("respStr " + respStr);
            }
        } catch (ClientProtocolException e) {
            log.error("sendHttpPostRequest : " +e);
        } catch (IOException e) {
            log.error("sendHttpPostRequest : " +e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return respStr;
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("amount", "1000");
        map.put("orderNo", "XEBEST20150413666666");
        map.put("status", "20");
        HttpRequestUtil.sendHttpPostRequest("http://192.168.26.1/cfca/test", map);
    }
}