HttpURLConnection 使用 方法内请求接口

HttpURLConnection 的使用:

HttpURLconnection是基于http协议的,支持get,post,put,delete等各种请求方式,最常用的就是get和post

做过微信支付的童鞋应该晓得这个东西.

利用HttpURLconnection去请求接口,从目标接口获得返回数据.

       
 /**
	 * 方法内请求接口
	 * 
	 * @param reqMsg
	 * @return
	 * @throws Exception
	 */
	public Map<String,String> requirest(ISOMsg reqMsg) {
	    try {
			//创建链接
			URL httpUrl = new URL("http://XXX");
			//打开连接
            HttpURLConnection Connection = (HttpURLConnection) httpUrl.openConnection();
            Connection.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            Connection.setDoOutput(true);
            Connection.setDoInput(true);
            }
            Connection.connect();
            
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(Connection.getOutputStream());
            // 发送请求参数
            printWriter.write("aa="+aa+"&bb="+bb);//post的参数 
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(Connection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while((len=bis.read(arr))!= -1){
                bos.write(arr,0,len);
                bos.flush();
            bos.close();
            String date = bos.toString("utf-8");//返回
            log.info("返回数据:"+date);
            //转成json
            Object json =JSON.parse(date);  
	    //json转map
            Map<String,String> map = (Map)json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reqMsg;
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值