网络访问之HttpURLConnection
来源:互联网 发布:windows开机声音 编辑:程序博客网 时间:2024/06/09 17:30
注意问题:
1、网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
2、url上如果有中文需要转码:
URLEncoder.encode("中文")
3、工具类,处理返回的流转换成字符串
public class StreamUtils { public static String is2Str(InputStream is) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = -1; byte[] buffer = new byte[1024]; while((len=is.read(buffer))!=-1){ baos.write(buffer, 0, len); } return baos.toString(); }}
get请求:
new Thread(new Runnable() { @Override public void run() { try { //1. 创建一个URL URL url = new URL(path); //开启一个Connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置参数,和超时时间 connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); // 开始连接 connection.connect(); int responseCode = connection.getResponseCode(); if (200 == responseCode) {//成功 InputStream is = connection.getInputStream(); String result = StreamUtils.is2Str(is); } else {//状态码不正确 } } catch (Exception e) {//异常 } }}).start();
post请求:
new Thread(new Runnable() { @Override public void run() { try { //创建一个URL URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); //设置是否允许给服务器上传数据(post) connection.setDoOutput(true); connection.connect();//可选 OutputStream os = connection.getOutputStream(); DataOutputStream out = new DataOutputStream(os); String params = "key1=value1&key2=value2"; //把我们的参数写出去 //os.write(params.getBytes()); out.writeBytes(params); //获取服务器的返回数据 InputStream is = connection.getInputStream(); String result = StreamUtils.is2Str(is); } catch (Exception e) { } }}).start();
补充:
1、将http关掉
connection.disconnect();
2、设置读取超时毫秒
connection.setReadTimeout(5000);
0 0
- 网络访问之HttpURLConnection
- 网络访问之HttpURLConnection
- Android 之 HttpURLConnection 访问网络
- 访问网络之HttpClient和HttpUrlConnection
- Android网络访问之HttpURLConnection和HttpClient
- Android之使用HttpURLConnection进行网络访问
- android网络访问之HttpURLConnection vs OkHttp
- Android网络访问之HttpURLConnection和HttpClient
- HttpURLConnection(访问网络)
- 使用HttpURLConnection访问网络
- HttpURLConnection访问网络
- 使用HttpURLConnection访问网络
- android HttpURLConnection网络访问
- 使用HttpURLConnection访问网络
- 用HttpURLConnection访问网络
- 使用HttpURLConnection访问网络
- 初学使用HttpURLConnection访问网络之发送GET请求
- Android之访问网络,使用HttpURLConnection还是HttpClient?
- Meta标签中的format-detection属性及含义
- 4.5.2.5_主线程_墨镜滤镜
- 模拟退火搜索算法
- classloader 深入理解
- 一站式学习Wireshark(一):Wireshark基本用法
- 网络访问之HttpURLConnection
- No such file or directory:Failed to chmod /Users/hthy/Library/Developer/CoreSimulator/Devices/125D87
- java高并发解决方案
- 4.6_结合剪辑区域绘制墨镜滤镜效果
- IAR forARM 建立第一个STM32F051的工程
- Hibernate中get和load的区别
- 伴随数组,可惜超时了
- Maven学习 (一) 搭建Maven环境
- JAVABEAN EJB POJO区别