Android中HttpURLConnection使用get方式向服务器提交json字符串

本文介绍了一种通过HTTP GET请求发送JSON数据并接收服务器响应的方法。具体包括JSON对象的创建与编码、发起网络请求、处理HTTP响应及解析返回的JSON数据等步骤。

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

核心代码:

<span style="font-size:18px;">private String mythrid(){
        String jsonStr = null;
        try {
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("2", "金色");
//          json字符串
            String jsonObjectStr =jsonObject.toString();
//          把json字符串要重新编码,否则在拼接在路径中,会出现乱码
            String jsonObjectStrEncoder = URLEncoder.encode(jsonObjectStr, "utf-8");
            //			连接网络6句话
            String path = "http://www.5ulm.cn/ws/product/getProdDetailByAttrs?keyAttrRefSaleAttrId=1&saleAttrs="+jsonObjectStrEncoder;
            Log.e("1","请求路径:"+path);
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");// 设置请求的方式
            connection.setReadTimeout(5000);// 设置超时的时间
            connection.setConnectTimeout(5000);// 设置链接超时的时间
            connection.setRequestProperty("Referer",path);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            // 设置请求的头
            connection
                    .setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
            if (connection.getResponseCode() == 200) {
                System.out.println("连接成功" + ">>>>>>>>>>>");
//				用getInputStream流直接获得json的数据
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bs = new byte[1024];
                int len = 0;
                while ((len = is.read(bs)) != -1) {
                    bos.write(bs, 0, len);
                }
//				字节流对象转化成字节数组
                byte[] bosData = bos.toByteArray();
//				字节数组转化成字符串然后进行解析
                jsonStr= new String(bosData, "UTF-8");
                Log.e("1","服务器返回的数据>>>"+jsonStr);
                return jsonStr;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;


    }</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值