HttpUrlConnect Get与Post请求

首先网络请求不能放于主线程,必须开启子线程操作
public static final String dataUrl = "http://guolin.tech/api/china";

Get请求:         

private void getData(){
    URL url;
    BufferedReader bufferedReader = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(Config.dataUrl);
         connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuffer = new StringBuilder();
        String line;
        while((line = bufferedReader.readLine())!=null){
            stringBuffer.append(line);
        }
        LogUtils.e("获取到的内容"+stringBuffer.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(connection!=null){
            connection.disconnect();
        }
        if(bufferedReader!=null){
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Post请求:

private void myPost(){
    URL url;
    BufferedReader bufferedReader = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(Config.dataUrl);
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes("username=admin&password=123456");
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while((line = reader.readLine())!=null){
                stringBuilder.append(line);
            }
            LogUtils.e("打印Post内容"+stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }finally {
        if(connection!=null){
            connection.disconnect();
        }
        if(bufferedReader!=null){
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值