HttpURLConnection 发送post,get请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HSH205572/article/details/84553978
package com.***.***.support.util;

import com.alibaba.fastjson.JSONObject;
import com.icinfo.frk.common.utils.StringUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;

import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 描述 ********
 *
 * @author ***
 * @date *******
 */
public class HttpUtil {

    /**
     * 描述 发送Post请求-编码格式默认 UTF-8
     *
     * @param path   请求路径
     * @param params 请求参数
     * @return
     * @author ***
     * @date 2018/11/26
     */
    public static String sendPostRequest(String path, Map<String, String> params, String encoding) throws Exception {
        //1 参数处理
        String paramString = null;
        if (MapUtils.isNotEmpty(params)) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> param = iterator.next();
                sb.append(param.getKey()).append("=");
                if (StringUtils.isNotEmpty(param.getValue())) {
                    sb.append(param.getValue());
                }
                sb.append("&");
            }

            paramString = sb.toString().substring(0, sb.length() - 1);
        }

        HttpURLConnection httpURLConnection = null;
        OutputStream ops = null;
        InputStream ips = null;
        BufferedReader br = null;
        try {
            //与服务器端建立连接通道
            httpURLConnection = (HttpURLConnection) new URL(path).openConnection();

            //设置请求方式为post
            httpURLConnection.setRequestMethod("POST");
            //是否允许向请求的输出流中写入数据 true允许,默认为false。
            //post请求因为参数要写入到输出流中,所以必须是true。
            httpURLConnection.setDoOutput(true);
            //当前的连接可以从服务器读取内容,默认为true。
            httpURLConnection.setDoInput(true);
            //设置连接超时限制为50s。单位毫秒
            httpURLConnection.setConnectTimeout(50000);
            //设置将读超时限制为50s。单位毫秒
            httpURLConnection.setReadTimeout(50000);
            //post请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            //设置请求字符编码
            httpURLConnection.setRequestProperty("Accept-Charset", encoding);

            if (StringUtil.isNotEmpty(paramString)) {
                byte[] paramByte = paramString.getBytes();
                httpURLConnection.setRequestProperty("content-length", String.valueOf(paramByte.length));
                //写入参数到正文
                ops = httpURLConnection.getOutputStream();
                ops.write(paramByte);
                ops.flush();
            }

            if (HttpStatus.SC_OK == httpURLConnection.getResponseCode()) {
                ips = httpURLConnection.getInputStream();
                br = new BufferedReader(new InputStreamReader(ips));
                String content;
                StringBuilder stringBuilder = new StringBuilder();
                while ((content = br.readLine()) != null) {
                    stringBuilder.append(content);
                }

                JSONObject jsonObject = JSONObject.parseObject(stringBuilder.toString());
                return jsonObject.toJSONString();
            }
        } catch (MalformedURLException e) {
            throw new MalformedURLException();
        } catch (ProtocolException e) {
            throw new ProtocolException();
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedEncodingException();
        } catch (IOException e) {
            throw new IOException();
        } finally {
            if (br != null) {
                br.close();
            }
            if (ips != null) {
                br.close();
            }
            if (ops != null) {
                ops.close();
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

        return null;
    }

    /**
     * 描述 发送GET请求
     *
     * @param path   请求路径
     * @param params 请求参数
     * @return
     * @author ***
     * @date 2018/11/26
     */
    public static String sendGetRequest(String path, Map<String, String> params, String ecoding) {
        InputStream inputStream;
        HttpURLConnection conn = null;
        try {
            StringBuilder url = new StringBuilder(path);
            url.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                url.append(entry.getKey()).append("=");
                url.append(URLEncoder.encode(entry.getValue(), ecoding));
                url.append("&");
            }
            url.deleteCharAt(url.length() - 1);

            conn = (HttpURLConnection) new URL(url.toString()).openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Connection", "Keep-Alive");
            if (conn.getResponseCode() == HttpStatus.SC_OK) {
                inputStream = conn.getInputStream();
                byte[] dateStream = readStream(inputStream);
                return new String(dateStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }

    /**
     * 描述 读取流
     *
     * @param inStream
     * @return byte[]
     * @author ***
     * @date 2018/11/26
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }

}

猜你喜欢

转载自blog.csdn.net/HSH205572/article/details/84553978