您的位置:首页 > 理论基础 > 计算机网络

HttpUrlConnection与HttpClient的认识(四) -HttpClient的封装

2017-06-20 11:23 375 查看
转载自:http://blog.csdn.net/u010248330/article/details/69372019

import org.apache.commons.httpclient.*;

import org.apache.commons.httpclient.methods.*;

import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.zip.GZIPInputStream;

public class HttpClientUtil {

    /**

     * 使用post方式调用

     * @param url 调用的URL

     * @param values 传递的参数值List

     * @param charSet设置内容的编码格式

     * @return 调用得到的字符串

     */

    public static String httpClientPost(String url,List<NameValuePair[]> values,String charSet){

        StringBuilder sb =new StringBuilder();

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(url);

        //创建参数队列

        for (NameValuePair[] value : values) {

            postMethod.addParameters(value);

        }

        try {

            httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charSet);

            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000);

            httpClient.getHttpConnectionManager().getParams().setSoTimeout(3000);

            int statusCode = httpClient.executeMethod(postMethod);

            if(statusCode != 200){

                return "";

            }

            //以流的行式读入,避免中文乱码

            InputStream is = postMethod.getResponseBodyAsStream();

            BufferedReader dis=new BufferedReader(new InputStreamReader(is,"utf-8"));   

             String str ="";                           

             while((str =dis.readLine())!=null){

                 sb.append(str);

                 sb.append("\r\n"); // 换行

             }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            postMethod.releaseConnection();

        }

        return sb.toString();

    }

    /**

     * 使用get方式调用

     * @param url调用的URL

     * @return 调用得到的字符串

     */

    public static String httpClientGet(String url,String charSet){

        StringBuilder sb =new StringBuilder();

        HttpClient httpClient = new HttpClient();

        GetMethod getMethod = new GetMethod(url);

        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

        try {

            // 执行getMethod

            httpClient.executeMethod(getMethod);

            //以流的行式读入,避免中文乱码

            InputStream is = getMethod.getResponseBodyAsStream();

            BufferedReader dis=new BufferedReader(new InputStreamReader(is,charSet));   

             String str ="";                           

             while((str =dis.readLine())!=null){

                 sb.append(str);

             }

        } catch (Exception e) {

             e.printStackTrace();

        } finally {

            // 关闭连接

            getMethod.releaseConnection();

        }

        return sb.toString(); 

    }

    /**

     * 将MAP转换成HTTP请求参数

     * @param pairArr

     * @return

     */

    public static NameValuePair[] praseParameterMap(Map<String, String> map){

        NameValuePair[] nvps = new NameValuePair[map.size()];

        Set<String> keys = map.keySet();

        int i=0;

        for(String key:keys){

            nvps[i] = new NameValuePair();

            nvps[i].setName(key);

            nvps[i].setValue(map.get(key));

            i++;

        }

        return nvps;

    }

    /**

     * 使用post方式调用

     * @param url 调用的URL

     * @param values 传递的参数值

     * @param xml 传递的xml参数

     * @return

     */

    public static String httpClientPost(String url, NameValuePair[] values, String xml){

        StringBuilder sb = new StringBuilder();

        HttpClient client = new HttpClient();

        client.getParams().setParameter(

                HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

        PostMethod method = new PostMethod(url);

        method.setQueryString(values);

        method.addRequestHeader("Content-Type", "text/xml;charset=UTF-8");

        RequestEntity reis = null;

        InputStream input = null;

        InputStream is = null;

        BufferedReader dis = null;

        try {

            input = new ByteArrayInputStream(xml.getBytes("utf-8"));

            reis = new InputStreamRequestEntity(input);

            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,

                    new DefaultHttpMethodRetryHandler());

            method.setRequestEntity(reis);

            client.executeMethod(method);

            // 以流的行式读入,避免中文乱码

            is = method.getResponseBodyAsStream();

            dis = new BufferedReader(new InputStreamReader(is, "utf-8"));

            String str = "";

            while ((str = dis.readLine()) != null) {

                sb.append(str);

            }

        } catch (HttpException ex) {

            ex.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            method.releaseConnection();

            try {

                if (dis != null)

                    dis.close();

                if (is != null)

                    is.close();

                if (input != null)

                    input.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return sb.toString();

    }

    public static String httpGzipGet(String url,String charset){

        HttpClient httpclient = new HttpClient();

        GetMethod method = new GetMethod(url);

        method.addRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");

        method.addRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");//gzip解压缩必须属性

        InputStream in = null;

        GZIPInputStream gzin = null;

        InputStreamReader isr = null;

        BufferedReader br = null;

        try {

            httpclient.executeMethod(method);

            if(method.getStatusCode() == HttpStatus.SC_OK){

                Header respHead = method.getResponseHeader("Content-Encoding");

                if(respHead != null){

                    String contEncoding = respHead.getValue();

                    if(contEncoding != null && contEncoding.toLowerCase().indexOf("gzip") > -1){

                        in = method.getResponseBodyAsStream();

                        gzin = new GZIPInputStream(in);

                        isr = new InputStreamReader(gzin,charset);

                        br = new BufferedReader(isr);

                        String temp = "";

                        StringBuffer result = new StringBuffer();

                        if((temp = br.readLine()) != null){

                            result.append(temp);

                        }

                        return result.toString();

                    }else{

                        return httpClientGet(url,charset);

                    }

                }else{

                    return null;

                }

            }else{

                return null;

            }

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        } finally{

            try{

                if(br != null){

                    br.close();

                    br = null;

                }

                if(isr != null){

                    isr.close();

                    isr = null;

                }

                if(gzin != null){

                    gzin.close();

                    gzin = null;

                }

                if(in != null){

                    in.close();

                    in = null;

                }

                if(method != null){

                    method.releaseConnection();

                    method = null;

                }

            }catch(IOException e){

                e.printStackTrace();

            }

        }

    }

    public static String httpClientPostJson(String url, String jsonStr){

        if (jsonStr == null)

            return null;

        StringBuilder sb = new StringBuilder();

        HttpClient httpClient = new HttpClient();

        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(300);

        httpClient.getHttpConnectionManager().getParams().setSoTimeout(700);

        PostMethod postMethod = new PostMethod(url);

        try {

            StringRequestEntity entity = new StringRequestEntity(jsonStr, "application/json", "utf-8");

            postMethod.setRequestEntity(entity);

            int statusCode = httpClient.executeMethod(postMethod);

            if (statusCode != 200) {

                return "";

            }

            //以流的行式读入,避免中文乱码

            InputStream is = postMethod.getResponseBodyAsStream();

            BufferedReader dis = new BufferedReader(new InputStreamReader(is, "utf-8"));

            String str;

            while ((str = dis.readLine()) != null) {

                sb.append(str);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            postMethod.releaseConnection();

        }

        return sb.toString();

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: