HttpURLConnection发送http请求

记录工作中经常使用的代码HttpURLConnection,一个小demo,用户使用时根据自己的需要进行自定义扩展

  1. 创建链接
 /**
     *@author lxw
     *@date 2020/7/2
     *@desc 创建http链接
     *@param [urlPath]
     *@return java.net.HttpURLConnection
    **/
    public static HttpURLConnection bulidConnect(String urlPath) throws Exception{
        URL url = new URL(urlPath);
        log.info("开始初始化服务器连接...");
        log.info("服务器地址:[ " + url + " ]");
        /**启用代理*/
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, Integer.valueOf(proxyProt)));
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("11.16.55.33", 8080));
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//下面属性根据需要设置
        httpURLConnection.setConnectTimeout(30000);
        httpURLConnection.setReadTimeout(30000);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.connect();
        log.info("服务器连接完成...");
        return httpURLConnection;
    }

2.发送数据

 /**
     *@author lxw
     *@date 2020/7/2
     *@desc 上送信息
     *@param [httpURLConnection, message]
     *@return void
    **/
    public static void sendMsg(HttpURLConnection httpURLConnection,String message) throws Exception {
        log.info("上送服务报文开始...");
        log.info("上送报文:[" + message + "]");
        OutputStream outputStream = null;
        try {
            outputStream = httpURLConnection.getOutputStream();
            // 注意编码格式,防止中文乱码
            if (StringUtils.isNotEmpty(message)) {
                outputStream.write(message.getBytes("UTF-8"));
            } else {
                outputStream.write("".getBytes());
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != outputStream)
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

3.接收信息

/**
     *@author lxw
     *@date 2020/7/2
     *@desc 接收响应信息,写入byte 存储,不存储本地
     *@param [httpURLConnection]
     *@return java.lang.String
    **/
    public static byte[] receiveMsg(HttpURLConnection httpURLConnection) throws IOException {
        log.debug("接收服务器响应报文开始...");
        InputStream in = null;
        BufferedInputStream bin =null;
        byte[] bytes =null;
        ByteArrayOutputStream byteArrayOutputStream =null;
        try {
            int code = httpURLConnection.getResponseCode();
            log.info("响应信息:{}",httpURLConnection.getHeaderField(2));
            //获取文件的字节长度
            if (200 == code) {
                in = httpURLConnection.getInputStream();
                bin = new BufferedInputStream(in);
                byteArrayOutputStream = new ByteArrayOutputStream();
                bytes = new byte[Integer.valueOf(httpURLConnection.getHeaderField(2))];
                int len = 0;
                while ((len=bin.read(bytes))!=-1){
                    byteArrayOutputStream.write(bytes,0,len);
                }
                log.info("下载图片大小:{}",byteArrayOutputStream.toByteArray().length);
            }
        } catch (NumberFormatException e) {
            throw new IOException("下载失败!");
        } catch (IOException e) {
            throw new IOException("下载失败!");
        }finally {
            if (byteArrayOutputStream !=null){
                byteArrayOutputStream.close();
            }
            if (bin!=null){
                bin.close();
            }
            if (in!=null){
               in.close();
            }
        }
        log.info("接收服务器响应报文完成");
        return byteArrayOutputStream.toByteArray();
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值