网络访问之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