HttpUtil

HttpUtil通用工具类

package com.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 使用两种Http请求方式,根据自己的喜好进行选择:
 * HttpClient是Apache的一个三方网络框架,用起来比较方便,开发快
 * HttpURLConnection是一个多用途、轻量级的http客户端,用起来没有那么方便,但更容易的扩展和优化
 * 
 * @author sunw
 */
public class HttpUtil {

    /**
     * 通过HttpClient的Get方式请求
     * @param url
     * @param param Map类型的键值对
     * @return 成功返回result,失败返回空串
     */
    public static String sendGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
//        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            if (param != null) {
                // 参数拼接
                StringBuffer paramStr = new StringBuffer();
                Iterator<Entry<String, String>> iterator = param.entrySet().iterator();
                // 将参数拼接为key=value&key2=value2形式
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = iterator.next();
                    paramStr.append(entry.getKey() + "=" + entry.getValue() + "&");
                }
                // 删除最后一个&符号,拼接给url
                if (!paramStr.toString().trim().equals("")) {
                    paramStr.deleteCharAt(paramStr.length() - 1);
                    url += "?" + paramStr;
                }
            }
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 通过HttpClient的Post方式请求,json格式提交
     * @param url
     * @param param json字符串,不可为空
     * @return 成功返回result,失败返回空串
     */
    public static String sendPost(String url, String json) {
        String resultString = "";
        // 若参数为空,则返回空
        if (StringUtils.isEmpty(json)) {
            return resultString;
        }
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 通过HttpURLConnection的Get方式请求
     * @param urlStr
     * @return
     */
    public static String executeGetMethod(String urlStr, Map<String, String> param) {
        String response = "";
        try {
            if (param != null) {
                // 参数拼接
                StringBuffer paramStr = new StringBuffer();
                Iterator<Entry<String, String>> iterator = param.entrySet().iterator();
                // 将参数拼接为key=value&key2=value2形式
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = iterator.next();
                    paramStr.append(entry.getKey() + "=" + entry.getValue() + "&");
                }
                // 删除最后一个&符号,拼接给url
                if (!paramStr.toString().trim().equals("")) {
                    paramStr.deleteCharAt(paramStr.length() - 1);
                    urlStr += "?" + paramStr;
                }
            }
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 连接超时时间
            connection.setConnectTimeout(5000);
            // 读取超时时间
            connection.setReadTimeout(5000);
            connection.connect();
            // 获得返回值
            InputStream in = connection.getInputStream();
            response = getResponse(in);
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 通过HttpURLConnection的Post方式请求
     * @param urlStr
     * @param paramStr json字符串,不可为空
     * @return 成功返回result,失败返回空串
     */
    public static String executePostMethod(String urlStr, String paramStr) {
        String response = "";
        if (StringUtils.isEmpty(paramStr)) {
            return response;
        }
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            // 允许打印
            connection.setDoOutput(true);
            // 设置缓存
            connection.setUseCaches(false);
            // 连接超时时间
            connection.setConnectTimeout(5000);
            // 读取超时时间
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Charset", "UTF-8");

            connection.setRequestProperty("Content-Length", String.valueOf(paramStr.length()));
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            // 写入请求的字符串
            out.writeBytes(paramStr);
            out.flush();
            out.close();

            // 获得返回值
            InputStream in = connection.getInputStream();
            response = getResponse(in);

            connection.disconnect();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static String getResponse(InputStream in) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder builder = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return builder.toString();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值