java工具

3.HttpUtil

3.1 HttpURLConnection

/**
 * 1.通过JDK网络类Java.net.HttpURLConnection;
 */
public class HttpURLConnectionUtil {
	/**
     * Http get请求
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String deGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();

        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.connect();
            if(connection.getResponseCode() == 200){
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }

    /**
     * Http post请求
     * @param httpUrl 连接
     * @param param 参数
     * @return
     */
    public static String doPost(String httpUrl, String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //拼装参数
            if (null != param && !param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            //设置权限
            //设置请求头等
            //开启连接
            connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }
}

3.2 commons-httpclient

public class HttpClient3Util {
	 /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤:
     * 1.生成一个HttpClient对象并设置相应的参数;
     * 2.生成一个GetMethod对象并设置响应的参数;
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
     * 4.处理响应状态码;
     * 5.若响应正常,处理HTTP响应内容;
     * 6.释放连接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1.生成HttpClient对象并设置参数
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
        } finally {
            //6.释放连接
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, String json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        RequestEntity requestEntity = new StringRequestEntity(json);
        postMethod.setRequestEntity(requestEntity);
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}

依赖

<dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
 </dependency>

3.3 httpcomponents

public class HttpClient4Util {

    private static HttpClient httpClient;

    private static Map map;

    static {
        httpClient = HttpClients.createDefault();
        map = new HashMap<String,String>();
    }

    public static String doGet(String url,Map<String,String> headerMap, Map<String,String> paramMap) {
        headerMap = initMap(headerMap);
        String paramStr = null;
        try {
            paramStr = EntityUtils.toString(exchangeParam(paramMap));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(paramStr != null && !paramStr.trim().equals("")){
            url = url + "?" + paramStr;
        }
        //创建方法实例
        HttpGet httpGet = new HttpGet(url);
        //设置请求头
        headerMap.put("Connection", "Close");
        setHeader(httpGet,headerMap);
        return httpClientExcute(httpClient,httpGet);
    }

    public static String doPostForm(String url,Map<String,String> headerMap,Map<String,String> paramMap){
        headerMap = initMap(headerMap);
        //创建方法实例
        HttpPost httpPost = new HttpPost(url);
        //设置请求头
        headerMap.put("Content-type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
        headerMap.put("Connection", "Close");
        setHeader(httpPost,headerMap);
        //设置请求参数
        httpPost.setEntity(exchangeParam(paramMap));
        //执行请求
        return httpClientExcute(httpClient,httpPost);
    }

    public static String doPostJson(String url,Map<String,String> headerMap,String paramJson){
        headerMap = initMap(headerMap);
        //创建方法实例
        HttpPost httpPost = new HttpPost(url);
        //设置请求头
        headerMap.put("Content-type", ContentType.APPLICATION_JSON.getMimeType());
        headerMap.put("Connection", "Close");
        setHeader(httpPost,headerMap);
        //设置请求参数
        httpPost.setEntity(new StringEntity(paramJson,Consts.UTF_8));
        //执行请求
        return httpClientExcute(httpClient,httpPost);
    }

    public static String doPostFile(){
        return null;
    }

    private static String httpClientExcute(HttpClient httpClient, HttpUriRequest httpRequest){
        try {
            HttpResponse execute = httpClient.execute(httpRequest);
            if(execute.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity entity = execute.getEntity();
                if(entity != null){
                    String obj = EntityUtils.toString(entity);
                    return obj;
                }
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void setHeader(HttpMessage httpMessage,Map<String,String> headerMap){
        if (headerMap != null && !headerMap.isEmpty()) {
            headerMap.entrySet().forEach(s -> {
                httpMessage.setHeader(s.getKey(), s.getValue());
            });
        }
    }

    private static HttpEntity exchangeParam(Map<String,String> paramMap){
        List formParams = new ArrayList<NameValuePair>();
        if (paramMap != null && !paramMap.isEmpty()) {
            for (String key:paramMap.keySet()) {
                formParams.add(new BasicNameValuePair(key,paramMap.get(key)));
            }
        }
        return new UrlEncodedFormEntity(formParams,Consts.UTF_8);
    }

    private static Map initMap(Map headerMap){
         if(headerMap == null){
            map.clear();
            headerMap = map;
   		}
    	return headerMap;
    }
 }

依赖

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.9</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值