selenium调用http

        JavascriptExecutor jse = (JavascriptExecutor) driver.getWebDriver() ;
        String resp="";
        try {
            resp = (String) jse.executeScript(
"var xmlhttp=new XMLHttpRequest();\n" +
"xmlhttp.open(\"POST\",\"https://***.com/***.do\",false);\n" +
"xmlhttp.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded; charset=UTF-8\");\n"+ // 表单提交的头部信息
"xmlhttp.send(\"type=normal&json=%7B%22test%22%3A1%7D&_csrf_token_="+csrf_token+"\");\n" +  // 表单数据
"return xmlhttp.responseText;");
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Assert.assertTrue(resp.contains("\"status\":true"));

selenium框架中封装后的方法

    public String jsPostRequest(String url, Map paras) {
        String codeBase = "var xmlhttp=new XMLHttpRequest();\nxmlhttp.open(\"POST\",\"#url\",false);\nxmlhttp.setRequestHeader(\"content-type\", \"application/x-www-form-urlencoded; charset=UTF-8\");\nxmlhttp.send(\"#paras\");\nreturn xmlhttp.responseText;";
        if (paras != null && paras.keySet() != null && paras.keySet().size() != 0) {
            String paraString = "";
            int index = 0;
            for(Iterator i$ = paras.keySet().iterator(); i$.hasNext(); ++index) {
                String key = (String)i$.next();
                if (index == 0) {
                    paraString = key + "=" + (String)paras.get(key);
                } else {
                    paraString = paraString + "&" + key + "=" + (String)paras.get(key);
                }
            }
            String jsCode = codeBase.replace("#url", url).replace("#paras", paraString);
            return this.jsExecute(jsCode);
        } else {
            return null;
        }
    }

        String url_1 = "https://baidu.com/gettestword.do";
        HashMap param_1 = new HashMap();
        try {
            param_1.put("type", URLEncoder.encode("normal","utf-8"));
            param_1.put("json", URLEncoder.encode("{\"channel\":1}","utf-8"));
            param_1.put("_csrf_token_", csrf_token);

        }catch (Exception e) {
            e.printStackTrace();
        }
        String result_1 = driver.jsPostRequest(url_1, param_1);
        System.out.println(result_1);

你可能感兴趣的:(selenium调用http)