Java两种拼接http Get请求参数URL连接地址的方法

直接上代码吧,简单直接,

第一种,用String.format()

第二种:用Uri构造器

    private static String fromDate = "2022-12-13"; //出发时间(格式:yyyy-mm-dd)
    private static String fromStation = "GZQ"; //出发站代号
    private static String toStation = "YCN"; //到达站代号
    private static String purposeCodes ="ADULT"; //乘客类型(成人:ADULT,学生:0X00)
    private static String baseUrl = "https://kyfw.12306.cn";
    private static String publicName = "/otn";
    private static String leftTicketUrl ="/leftTicket/query"; //"leftTicket/queryT";
    //注:12306的查询接口经常改变(可能一天一改),其变动的主要规律为:https://kyfw.12306.cn/otn/leftTicket/query[A-Z],就是最后一个字母做变动。
    // 因此,如果程序查询出异常,很大可能就是接口改变了,重新抓下查询接口即可。
    private static String getTicketListUrlFmt = baseUrl + publicName  + "%s?" +
            "leftTicketDTO.train_date=%s&" +
            "leftTicketDTO.from_station=%s&" +
            "leftTicketDTO.to_station=%s&" +
            "purpose_codes=%s";


    public static void main(String[] args) throws IOException, URISyntaxException {

        String getTicketListUrl = String.format(getTicketListUrlFmt, leftTicketUrl, fromDate, fromStation, toStation, purposeCodes);
        System.out.println(getTicketListUrl);

        //uri的构造器
        URI uri = new URIBuilder()
                .setScheme("https")
                .setHost("kyfw.12306.cn")
                .setPath(publicName+leftTicketUrl)
                .setParameter("leftTicketDTO.train_date", fromDate )
                .setParameter("leftTicketDTO.from_station", fromStation)
                .setParameter("leftTicketDTO.to_station", toStation)
                .setParameter("purpose_codes", purposeCodes)
                .build();
        System.out.println(uri.toString());


    }

执行效果如下图:一模一样:

你可能感兴趣的:(Java,java,http,Uri,URL,拼接)