简体   繁体   English

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

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

I have a following functionality: I create through the user form a new user. 我具有以下功能:通过用户表单创建一个新用户。 After i had submitted the entered data, created user get the bar-code, which would be used for get access to the other system section by scanning that bar-code with hand-scanner. 在我提交了输入的数据之后,创建的用户将获得条形码,该条形码可通过使用手动扫描仪扫描该条形码来访问其他系统部分。 So how can i get any value (in my case that bar-code from json calls (Post, Get, JSON) with Selenium WebDriver on Java? 那么,如何在Java上使用Selenium WebDriver获取任何值(以json条形码(Post,Get,JSON)中的条形码为例)呢?

Selenium has nothing to do with json. Selenium与json无关。 You can use Apache HttpClient library for sending GET, POST, PUT and DELETE requests and receiving the responses. 您可以使用Apache HttpClient库发送GET,POST,PUT和DELETE请求并接收响应。 Given below is a simplified function for all cases. 下面给出的是所有情况下的简化功能。

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;
    }
}

Selenium only deals with browsers. 硒仅与浏览器打交道。 Java has classes that do http requests. Java具有执行http请求的类。

see the code below: 参见下面的代码:

  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.

相关问题 如何使用Selenium Webdriver和Java从元素中获取文本? - How can I get text from element with Selenium webdriver and Java? Java:如何从脚本标签获取JSON值? - Java: How can I get JSON value from a script tag? 使用Selenium Webdriver从POST获取响应值 - Get response value from POST with Selenium webdriver Selenium从WebDriver获取HTML(或JSON)响应 - Selenium get HTML (or JSON) response from WebDriver 如何在Selenium Webdriver(Java)中从Web元素获取数值 - How to get a numeric value from a webelement in Selenium Webdriver (Java) 如何从中获取价值 <h3> Java Selenium WebDriver中的标记 - How to get value from <h3> tag in Selenium WebDriver, Java 如何使用 org.json 库从 Java 中的 JSON 文件中获取每个键和值? - How can I get every key and value from a JSON file in Java using the org.json library? 在Selenium WebDriver中使用Java在ID或任何属性中不存在值时如何从禁用的文本字段中获取值 - How to get value from a disabled text field when the value is not present in ID or in any attribute using Java in Selenium WebDriver 如何通过Java获取响应值(json)到字符串 - how can I get response value (json) to String via Java 如何修改此字符串并从 Java 中的 JSON 对象获取我想要的值? - How can i modify this string and get the value I want from JSON Object in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM