HttpURLConnection继承了URLConnection,因此它也可以使用get或post发送请求。HttpURLConnection对URLConnection做了一定的封装,使用起来更加的方便一些。
可以这样获得
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
它还提供了几个方便的方法:
获取响应代码
获取响应信息
获取请求方法
设置请求方法
其他的一些用法与URLConnection一样。
比如Get请求
URL url = new URL("http://192.168.1.103:3000/wb/index.html?key1=value1");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(3 * 1000);
urlConnection.connect();
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null){
Log.i("log", line);
}
比如Post请求
URL url = new URL("http://192.168.1.103:3000/wb/index.html");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("name", "test");
urlConnection.setConnectTimeout(3 * 1000);
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write("key1=value1&key2=value2".getBytes());
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null){
Log.e("log1", line);
}
尊重作者,转载请注明出处!
版权申明:本文版权归作者所有,未经授权,任何单位或个人不得以任何形式转载、摘编或利用其它方式使用本博客内容。作者保留追究相关法律责任的权利。如需使用博客内容,请与作者联系获得授权。感谢对本文的尊重与支持。
免责声明:本网站所载内容仅供参考,不构成任何专业建议。用户基于本网站内容作出的决策,风险自担。对于因使用本网站内容而产生的任何直接或间接损失,本网站不承担任何责任。请用户审慎判断,理性使用。