安卓中的HTTP的POST请求用法

该代码示例展示了一个名为MyUrl的Java线程类,它扩展了Thread。这个类用于执行POST方法的HTTP请求,设置超时时间,并处理输入/输出流。参数包括URL,请求参数,以及错误处理。当响应码为200时,读取并打印返回的JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

public class MyUl extends Thread{
   //获取网址传值
    String str;
    
    public MyUl(String str) {
        this.str = str;
    }

    public void run() {
        super.run();
        try {
            URL url = new URL(str);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();
            String params = "pageSize=10&currentPage=1";
            //获取输出流
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(params.getBytes());
            //关流
            outputStream.flush();
            //判断是否链接
            if (connection.getResponseCode() == 200){
                InputStream inputReader = connection.getInputStream();
                StringBuilder builder = new StringBuilder();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len=inputReader.read(bytes))!=-1){
                    builder.append(new String(bytes, 0, len));
                }
                String json = builder.toString();
                //得到值打印到控制台
                Log.i("tyx",json);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值