您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection GET和POST请求示例

2016-05-23 20:21 567 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  GET POST