HttpURLConnection的请求

   
    private void getHealthInfoForGet(){


        try {
            //填入请求地址
            URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f697 3049e6be");
            //打开链接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接服务的时间
            connection.setConnectTimeout(5 * 1000);
            //设置读取服务返回的数据的时间
            connection.setReadTimeout(5 * 1000);

            //等待服务器响应
            //得到服务的响应码
            int code = connection.getResponseCode();
            if(code == 200){//判断服务是否响应成功
                //读取服务器所放回来的数据信息
                InputStream is = connection.getInputStream();

                String info = StreamTools.readFromNetWork(is);

                System.out.println("结果 : "+info);


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

    }

   
    private void getHealthInfoForPost(){


        try {
            URL url = new URL("http://japi.juhe.cn/health_knowledge/categoryList");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //一定要大写
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            //设置请求参数 (POST)
            OutputStream os = connection.getOutputStream();
            os.write(("key=eb033dfcf95c03f9f451f697 3049e6be").getBytes());
            os.flush();


            //等待服务器响应
            int code = connection.getResponseCode();

            if(code == 200){

                //获取服务器的内容
                InputStream is = connection.getInputStream();

                String info = StreamTools.readFromNetWork(is);

                System.out.println("-->"+info);
            }

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


    }

public class StreamTools {

   
    public static String readFromNetWork(InputStream is){


        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }

            return baos.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;


    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值