繁体   English   中英

如何在Java上使用Selenium WebDriver从json调用(发布,获取,JSON)中获取任何值?

[英]How can i get any value from json calls (Post, Get, JSON) with Selenium WebDriver on Java?

我具有以下功能:通过用户表单创建一个新用户。 在我提交了输入的数据之后,创建的用户将获得条形码,该条形码可通过使用手动扫描仪扫描该条形码来访问其他系统部分。 那么,如何在Java上使用Selenium WebDriver获取任何值(以json条形码(Post,Get,JSON)中的条形码为例)呢?

Selenium与json无关。 您可以使用Apache HttpClient库发送GET,POST,PUT和DELETE请求并接收响应。 下面给出的是所有情况下的简化功能。

public static HttpResponse sendRequest(String requestType, String body,String url,
        String... headers) throws Exception {
    try {

        HttpGet getRequest = null;
        HttpPost postRequest;
        HttpPut putRequest;
        HttpDelete delRequest;
        HttpResponse response = null;
        HttpClient client = new DefaultHttpClient();

        // Collecting Headers
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String arg : headers) {

//Considering that you are applying header name and values in String format like this "Header1,Value1"

            nvps.add(new BasicNameValuePair(arg.split(",")[0], arg
                    .split(",")[1]));
        }
        System.out.println("Total Headers Supplied " + nvps.size());

        if (requestType.equalsIgnoreCase("GET")) {
            getRequest = new HttpGet(url);
            for (NameValuePair h : nvps) {
                getRequest.addHeader(h.getName(), h.getValue());
            }
            response = client.execute(getRequest);
        }

        if (requestType.equalsIgnoreCase("POST")) {
            postRequest = new HttpPost(url);
            for (NameValuePair h : nvps) {
                postRequest.addHeader(h.getName(), h.getValue());       
            }

            StringEntity requestEntity = new StringEntity(body,"UTF-8");
            postRequest.setEntity(requestEntity);
            response = client.execute(postRequest);
        }

        if (requestType.equalsIgnoreCase("PUT")) {
            putRequest = new HttpPut(url);
            for (NameValuePair h : nvps) {
                putRequest.addHeader(h.getName(), h.getValue());
            }
            StringEntity requestEntity = new StringEntity(body,"UTF-8");
            putRequest.setEntity(requestEntity);
            response = client.execute(putRequest);
        }

        if (requestType.equalsIgnoreCase("DELETE")) {
            delRequest = new HttpDelete(url);
            for (NameValuePair h : nvps) {
                delRequest.addHeader(h.getName(), h.getValue());
            }
            response = client.execute(delRequest);
        }

        return response;

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

硒仅与浏览器打交道。 Java具有执行http请求的类。

参见下面的代码:

  private HttpURLConnection setODataConnection(String url, String method) {
    try {
      URL obj = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

      conn.setRequestMethod(method);

      // add request header
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setRequestProperty("Accept", "application/json;odata=verbose");
      return conn;
    } catch (Exception e) {
      Assert.fail(e.getMessage());
      return null;
    }
  }

  private StringBuilder sendODataRequest(HttpURLConnection conn) {
    try {
      int responseCode = conn.getResponseCode();
      String method = conn.getRequestMethod();
      System.out.println("\nSending '" + method + "' request to URL : " + conn.getURL());
      System.out.println("Response Code : " + responseCode);

      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String inputLine;
      StringBuilder response = new StringBuilder();

      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }
      in.close();
      return response;
    } catch (Exception e) {
      Assert.fail(e.getMessage());
      return null;
    }
  }

  private ArrayList<String> getByFullUrl(String fullUrl, String entity) {
    HttpURLConnection conn = setODataConnection(fullUrl, "GET");
    StringBuilder response = sendODataRequest(conn);

    ArrayList<String> s = new ArrayList<String>();
    Pattern p = Pattern.compile(entity + "\" : (.*?)\\}");

    Matcher m = p.matcher(response);
    while (m.find()) {
      s.add(m.group(1).replace("\"", ""));
    }

    return s;
  }

  public ArrayList<String> get(String table, String entity) {
    String url = oDataUrl + table + "?$select=" + entity;
    return getByFullUrl(url, entity);
  }


  public void post(String table, String bodyDetails) {
    String url = oDataUrl + table;
    HttpURLConnection conn = setODataConnection(url, "POST");

    conn.setDoOutput(true);
    try {
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes("details={" + bodyDetails + "}");
      wr.flush();
      wr.close();
    } catch (Exception e) {
      Assert.fail(e.getMessage());
    }

    sendODataRequest(conn);
  }

  public void put(String table, String id, String bodyDetails) {
    String url = oDataUrl + table + "(" + id + ")";
    HttpURLConnection conn = setODataConnection(url, "PUT");

    conn.setDoOutput(true);
    try {
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes("details={" + bodyDetails + "}");
      wr.flush();
      wr.close();
    } catch (Exception e) {
      Assert.fail(e.getMessage());
    }

    sendODataRequest(conn);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM