Java实现http请求

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {

    public final static int PAGE_MAX_LEN = 1024 * 1024;

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发送Get请求
     * 
     * @param url
     * @param params
     * @return 
     * @throws UnsupportedEncodingException
     */
    public static String httpGet(String url, Map<String, String> params) {
        HttpClient httpClient = new HttpClient();
        GetMethod method = null;
        try {
            if ((params == null) || (params.size() <= 0)) {
                method = new GetMethod(url);
            } else {
                String param = buildParam(params);
                method = new GetMethod(url + "?" + param);
            }
            int statusCode = httpClient.executeMethod(method);
            if ((statusCode == HttpStatus.SC_BAD_REQUEST) || (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
                throw new HttpException("Method failed: " + method.getStatusLine());
            }
            InputStream inputStream = method.getResponseBodyAsStream();
            if (null == inputStream) {
                return null;
            }
            return getContent(inputStream);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }

        }
        return null;
    }

    /**
     * 发送Post请求
     * 
     * @param url 访问服务地址
     * @param params 参数
     * @return
     */
    public static String httpPost(String url, Map<String, String> params) {
        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        if ((params != null) && (params.size() > 0)) {
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            int i = 0;
            for (Entry<String, String> entry : params.entrySet()) {
                nameValuePairs[i] = new NameValuePair(entry.getKey(), entry.getValue());
                i++;
            }
            postMethod.setRequestBody(nameValuePairs);
        }
        try {
            int statusCode = client.executeMethod(postMethod);
            if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_CREATED)) {
                throw new HttpException("Method failed: " + postMethod.getStatusLine());
            }
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            if (null == inputStream) {
                return null;
            }
            return getContent(inputStream);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();// 释放连接
        }
        return null;
    }

    /**
     * json post请求http数据报
     * 
     * @param url 请求地址
     * @param packet json格式请求参数
     * @return
     */
    public static String httpJsonPost(String url, String packet) {
        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            postMethod.setRequestEntity(new StringRequestEntity(packet, "application/json", "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.getMessage(), e1);
        }
        try {
            int statusCode = client.executeMethod(postMethod);
            if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_CREATED)) {
                throw new HttpException("Method failed: " + postMethod.getStatusLine());
            }
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            if (null == inputStream) {
                return null;
            }
            return getContent(inputStream);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();// 释放连接
        }
        return null;
    }

    /**
     * 发送Delete请求
     * 
     * @param url 访问服务地址
     * @param params 参数
     * @return
     */
    public static boolean httpDelete(String url, Map<String, String> params) {
        HttpClient client = new HttpClient();
        DeleteMethod deleteMethod = new DeleteMethod(url);
        deleteMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        if ((params != null) && (params.size() > 0)) {
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            int i = 0;
            for (Entry<String, String> entry : params.entrySet()) {
                nameValuePairs[i] = new NameValuePair(entry.getKey(), entry.getValue());
                i++;
            }
            deleteMethod.setQueryString(nameValuePairs);
        }
        try {
            int statusCode = client.executeMethod(deleteMethod);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpException("Method failed: " + deleteMethod.getStatusLine());
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            deleteMethod.releaseConnection();// 释放连接
        }
    }

    /**
     * 构建key=value键值对类型参数
     * 
     * @param params
     * 
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String buildParam(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        for (Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            sb.append("&");
        }
        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : sb.toString();
    }

    /**
     * InputStream转换
     * 
     * @param is
     * @return
     * @throws IOException
     */
    public static String getContent(InputStream is) throws IOException {
        StringBuilder out = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return out.toString();
    }

    /**
     * 发送Get请求下载文件
     * 
     * @param url
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    public static File httpGetFile(String url, Map<String, String> params) {
        HttpClient httpClient = new HttpClient();
        GetMethod method = null;
        try {
            if ((params == null) || (params.size() <= 0)) {
                method = new GetMethod(url);
            } else {
                String param = buildParam(params);
                method = new GetMethod(url + "?" + param);
            }
            int statusCode = httpClient.executeMethod(method);
            if ((statusCode == HttpStatus.SC_BAD_REQUEST) || (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
                throw new HttpException("Method failed: " + method.getStatusLine());
            }

            Header[] contentDispositionHeader = method.getRequestHeaders("Content-disposition");
            Pattern p = Pattern.compile(".*filename=\"(.*)\"");
            Matcher m = p.matcher(contentDispositionHeader[0].getValue());
            m.matches();
            String fileName = m.group(1);
            if (StringUtils.isBlank(fileName)) {
                return null;
            }
            InputStream inputStream = method.getResponseBodyAsStream();
            if (null == inputStream) {
                return null;
            }
            String[] name_ext = fileName.split("\\.");
            File localFile = CustomFileUtil.createTmpFile(inputStream, name_ext[0], name_ext[1]);
            return localFile;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }

        }
        return null;
    }

    /**
     * 上传文件-POST
     * 
     * @param url
     * @param targetFile
     * @return
     */
    public static String httpPostWithFile(String url, File targetFile) {
        if (StringUtils.isEmpty(url)) {
            logger.info("Param: url is null");
            return null;
        }
        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        // 通过以下方法可以模拟页面参数提交
        // postMethod.setParameter("", "");

        try {
            // FilePart:用来上传文件的类,file即要上传的文件
            Part[] parts = { new FilePart("media", targetFile) };
            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
            postMethod.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8");

            // 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
            client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);
            int statusCode = client.executeMethod(postMethod);
            if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_CREATED)) {
                throw new HttpException("Method failed: " + postMethod.getStatusLine());
            }
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            if (null == inputStream) {
                return null;
            }
            return getContent(inputStream);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        } catch (HttpException e1) {
            logger.error(e1.getMessage(), e1);
        } catch (IOException e2) {
            logger.error(e2.getMessage(), e2);
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

}


你可能感兴趣的:(Java实现http请求)