HttpUtil

来源:互联网 发布:网络教研平台 编辑:程序博客网 时间:2024/06/06 18:40
import java.io.ByteArrayOutputStream;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpPut;import org.apache.http.entity.BufferedHttpEntity;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.log4j.Logger;import java.net.URL;import java.net.URLConnection;import java.io.InputStream;public class HttpUtil {    private static Logger log = Logger.getLogger(HttpUtil.class);    /**     * 以Post方法访问     *      * @param url     *            请求地址     * @param argsMap     *            携带的参数     * @return String 返回结果     * @throws Exception     */    @SuppressWarnings("deprecation")    public static String POSTMethod(String url, Map<String, Object> argsMap) {        String result = "SUCCESS";        try {            byte[] dataByte = null;            HttpClient httpClient = new DefaultHttpClient();            // 设置超时时间            RequestConfig requestConfig = RequestConfig.custom()                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)                    .setSocketTimeout(5000).build();            HttpPost httpPost = new HttpPost(url);            httpPost.setConfig(requestConfig);            // 设置参数            UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(                    setHttpParams(argsMap), "UTF-8");            httpPost.setEntity(encodedFormEntity);            // 执行请求            HttpResponse httpResponse = httpClient.execute(httpPost);            if (!checkNetwork(httpResponse)) {                result = "FAILURE,NETWORK ANOMALY!";                return result;            }            // 获取返回的数据            HttpEntity httpEntity = httpResponse.getEntity();            if (httpEntity != null) {                byte[] responseBytes = getData(httpEntity);                dataByte = responseBytes;                httpPost.abort();            }            // 将字节数组转换成为字符串            result = bytesToString(dataByte);        } catch (Exception e) {            result = "FAILURE";            log.error("POSTMethod 方法异常:" + e);        }        return result;    }    /**     * POST请求一个字符串, Add by gaonaifeng     *      * @param url     * @param param     * @return     */    @SuppressWarnings("deprecation")    public static String POSTMethod(String url, String param) {        String result = "SUCCESS";        try {            byte[] dataByte = null;            HttpClient httpClient = new DefaultHttpClient();            RequestConfig requestConfig = RequestConfig.custom()                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)                    .setSocketTimeout(5000).build();            HttpPost httpPost = new HttpPost(url);            httpPost.setConfig(requestConfig);            // 设置参数            StringEntity encodedFormEntity = new StringEntity(param, "UTF-8");            httpPost.setEntity(encodedFormEntity);            // 执行请求            HttpResponse httpResponse = httpClient.execute(httpPost);            // if (!checkNetwork(httpResponse)) {            // result = "FAILURE,NETWORK ANOMALY!";            // return result;            // }            // 获取返回的数据            HttpEntity httpEntity = httpResponse.getEntity();            if (httpEntity != null) {                byte[] responseBytes = getData(httpEntity);                dataByte = responseBytes;                httpPost.abort();            }            // 将字节数组转换成为字符串            result = bytesToString(dataByte);        } catch (Exception e) {            result = "FAILURE";            log.error("POSTMethod 方法异常:" + e);        }        return result;    }    /**     * POST请求一个byte数组, Add by gaonaifeng     *      * @param url     * @param param     * @return     */    @SuppressWarnings("deprecation")    public static String POSTMethod(String url, byte[] bytes) {        String result = "SUCCESS";        try {            byte[] dataByte = null;            HttpClient httpClient = new DefaultHttpClient();            RequestConfig requestConfig = RequestConfig.custom()                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)                    .setSocketTimeout(5000).build();            HttpPost httpPost = new HttpPost(url);            httpPost.setConfig(requestConfig);            // 设置参数            ByteArrayEntity encodedFormEntity = new ByteArrayEntity(bytes);            httpPost.setEntity(encodedFormEntity);            // 执行请求            HttpResponse httpResponse = httpClient.execute(httpPost);            // 获取返回的数据            HttpEntity httpEntity = httpResponse.getEntity();            if (httpEntity != null) {                byte[] responseBytes = getData(httpEntity);                dataByte = responseBytes;                httpPost.abort();            }            // 将字节数组转换成为字符串            result = bytesToString(dataByte);        } catch (Exception e) {            result = "FAILURE";            log.error("POSTMethod 方法异常:" + e);        }        return result;    }    /**     * 以Get方法访问     *      * @param url     *            请求地址     * @return String     * @throws Exception     */    @SuppressWarnings("deprecation")    public static String GETMethod(String url, Map<String, Object> argsMap) {        String result = "SUCCESS";        try {            byte[] dataByte = null;            HttpClient httpClient = new DefaultHttpClient();            RequestConfig requestConfig = RequestConfig.custom()                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)                    .setSocketTimeout(5000).build();            // 为GET请求链接构造参数            url = formatGetParameter(url, argsMap);            HttpGet httpGet = new HttpGet(url);            httpGet.setConfig(requestConfig);            HttpResponse httpResponse = httpClient.execute(httpGet);            if (!checkNetwork(httpResponse)) {                result = "FAILURE,NETWORK ANOMALY!";                return result;            }            HttpEntity httpEntity = httpResponse.getEntity();            if (httpEntity != null) {                byte[] responseBytes = getData(httpEntity);                dataByte = responseBytes;                httpGet.abort();            }            // 将字节数组转换成为字符串            result = bytesToString(dataByte);        } catch (Exception e) {            result = "FAILURE,NETWORK ANOMALY!";            log.error("GETMethod 方法异常:" + e);        }        return result;    }    // 检查url是否存在    public static Boolean CheckUrlValid(String url) {        long start=System.currentTimeMillis();        try {            URL httpUrl = new URL(url);//创建URL对象。              URLConnection uc = httpUrl.openConnection();//创建一个连接对象。              uc.setReadTimeout(3000);            uc.setConnectTimeout(3000);            InputStream in = uc.getInputStream();            log.info("检查url是否存在-url:" + url + ",时间:" + (System.currentTimeMillis()-start));            return true;        } catch (Exception e) {            log.info("检查url是否存在-异常-url:" + url + ",时间:" + (System.currentTimeMillis()-start));            return false;        }    }    /**     * 以Put方法访问     *      * @param url     *            请求地址     * @param argsMap     *            携带的参数     * @return String     * @throws Exception     */    @SuppressWarnings("deprecation")    public static String PUTMethod(String url, Map<String, Object> argsMap) {        String result = "SUCCESS";        try {            byte[] dataByte = null;            HttpClient httpClient = new DefaultHttpClient();            RequestConfig requestConfig = RequestConfig.custom()                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)                    .setSocketTimeout(5000).build();            HttpPut httpPut = new HttpPut(url);            httpPut.setConfig(requestConfig);            // 设置参数            UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(                    setHttpParams(argsMap), "UTF-8");            httpPut.setEntity(encodedFormEntity);            // 执行请求            HttpResponse httpResponse = httpClient.execute(httpPut);            if (!checkNetwork(httpResponse)) {                result = "FAILURE,NETWORK ANOMALY!";                return result;            }            // 获取返回的数据            HttpEntity httpEntity = httpResponse.getEntity();            if (httpEntity != null) {                byte[] responseBytes = getData(httpEntity);                dataByte = responseBytes;                httpPut.abort();            }            // 将字节数组转换成为字符串            result = bytesToString(dataByte);        } catch (Exception e) {            result = "FAILURE,NETWORK ANOMALY!";            log.error("PUTMethod 方法异常:" + e);        }        return result;    }    /**     * 以Put方法访问     *      * @param url     *            请求地址     * @param argsMap     *            携带的参数     * @return String     * @throws Exception     */    @SuppressWarnings("deprecation")    public static String PUTMethod(String url, String params) {        String result = "SUCCESS";        try {            byte[] dataByte = null;            HttpClient httpClient = new DefaultHttpClient();            RequestConfig requestConfig = RequestConfig.custom()                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)                    .setSocketTimeout(5000).build();            HttpPut httpPut = new HttpPut(url);            httpPut.setConfig(requestConfig);            // 设置参数            // 设置参数            StringEntity encodedFormEntity = new StringEntity(params, "UTF-8");            httpPut.setEntity(encodedFormEntity);            // 执行请求            HttpResponse httpResponse = httpClient.execute(httpPut);            if (!checkNetwork(httpResponse)) {                result = "FAILURE,NETWORK ANOMALY!";                return result;            }            // 获取返回的数据            HttpEntity httpEntity = httpResponse.getEntity();            if (httpEntity != null) {                byte[] responseBytes = getData(httpEntity);                dataByte = responseBytes;                httpPut.abort();            }            // 将字节数组转换成为字符串            result = bytesToString(dataByte);        } catch (Exception e) {            result = "FAILURE,NETWORK ANOMALY!";            log.error("PUTMethod 方法异常:" + e);        }        return result;    }    /**     * 构造GET请求地址的参数拼接     *      * @param url     * @param argsMap     * @return String     */    private static String formatGetParameter(String url,            Map<String, Object> argsMap) {        if (argsMap != null && !argsMap.isEmpty()) {            if (url != null && url.length() > 0) {                if (!url.endsWith("?")) {                    url = url + "?";                }                Set<Entry<String, Object>> entrySet = argsMap.entrySet();                Iterator<Entry<String, Object>> iterator = entrySet.iterator();                while (iterator.hasNext()) {                    Entry<String, Object> entry = iterator.next();                    if (entry != null) {                        String key = entry.getKey();                        String value = (String) entry.getValue();                        url = url + key + "=" + value;                        if (iterator.hasNext()) {                            url = url + "&";                        }                    }                }            }        }        return url;    }    /**     * 获取数据     *      * @param httpEntity     * @return     * @throws Exception     */    private static byte[] getData(HttpEntity httpEntity) throws Exception {        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(                httpEntity);        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        bufferedHttpEntity.writeTo(byteArrayOutputStream);        byte[] responseBytes = byteArrayOutputStream.toByteArray();        return responseBytes;    }    /**     * 设置HttpPost请求参数     *      * @param argsMap     * @return BasicHttpParams     */    private static List<BasicNameValuePair> setHttpParams(            Map<String, Object> argsMap) {        List<BasicNameValuePair> nameValuePairList = new ArrayList<BasicNameValuePair>();        // 设置请求参数        if (argsMap != null && !argsMap.isEmpty()) {            Set<Entry<String, Object>> set = argsMap.entrySet();            Iterator<Entry<String, Object>> iterator = set.iterator();            while (iterator.hasNext()) {                Entry<String, Object> entry = iterator.next();                BasicNameValuePair basicNameValuePair = new BasicNameValuePair(                        entry.getKey(), entry.getValue().toString());                nameValuePairList.add(basicNameValuePair);            }        }        return nameValuePairList;    }    /**     * 将字节数组转换成字符串     *      * @param bytes     * @return     * @throws UnsupportedEncodingException     */    private static String bytesToString(byte[] bytes)            throws UnsupportedEncodingException {        if (bytes != null) {            String returnStr = new String(bytes, "utf-8");            return returnStr;        }        return null;    }    /**     * 判断网络连接是否成功     *      * @author liuzhen     * @param httpResponse     * @return 成功true 失败false     */    public static boolean checkNetwork(HttpResponse httpResponse) {        if (httpResponse.getStatusLine().getStatusCode() == 200) {            return true;        }        return false;    }}
1 0
原创粉丝点击