HttpURLConnection GET和POST请求示例

本文介绍了使用Java发起HTTP GET和POST请求的具体实现方法。GET请求用于获取服务器资源,而POST请求则用于发送数据到服务器。示例代码展示了如何设置连接超时、请求方法以及如何读取响应内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.GET:

String _path = "http://*:8080/hpwy/token?appId=1234&secret=1234";
            URL _url = new URL(_path);
            HttpURLConnection _conn = (HttpURLConnection)  _url.openConnection();
            InputStream _input;
            byte[] _buffer = new byte[1024];
            long _length = 0;
            String _s;
            _conn.setConnectTimeout(5 * 1000);
            _conn.setRequestMethod("GET");
            _conn.setDoInput(true);
            _input = _conn.getInputStream();
            _length = _input.read(_buffer);
            _s = new String(_buffer,0, (int)_length);

2.POST

           if (null == _token || _token.length() <= 0)
                return;
            String _path = "http://*:8080/hpwy/login/phone";
            String _stringEntity;
            String _resultContent;
            int _length;
            byte[] _byteEntity;
            byte[] _buffer = new byte[1024];
            JSONObject _jsonEntity;
            OutputStream _outputStream;
            InputStream _inputStream;


            _jsonEntity = new JSONObject();
            _jsonEntity.put("phone", "1591234567");
            _jsonEntity.put("token", _token);
            _stringEntity = _jsonEntity.toString();
            _byteEntity = _stringEntity.getBytes(Charset.forName("UTF-8"));
            URL _url = new URL(_path);
            HttpURLConnection _conn = (HttpURLConnection) _url.openConnection();
            _conn.setConnectTimeout(5 * 1000);
            _conn.setRequestMethod("POST");
            _conn.setRequestProperty("accept", "*/*");
            _conn.setRequestProperty("connection", "Keep-Alive");
            _conn.setRequestProperty("Content-Type", "application/json");
            _conn.setDoInput(true);
            _conn.setDoOutput(true);

            _outputStream = _conn.getOutputStream();
            _outputStream.write(_byteEntity);
            _outputStream.flush();

            _inputStream = _conn.getInputStream();
            _length = _inputStream.read(_buffer);

            _resultContent = new String(_buffer, 0, _length);
            Log.d("hpwy", _resultContent);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值