F1laret
F1laret

Reputation: 19

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?

Upvotes: 0

Views: 4155

Answers (2)

Abhishek_Mishra
Abhishek_Mishra

Reputation: 4621

Selenium has nothing to do with json. You can use Apache HttpClient library for sending GET, POST, PUT and DELETE requests and receiving the responses. 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;
    }
}

Upvotes: 1

user3723314
user3723314

Reputation: 67

Selenium only deals with browsers. Java has classes that do http requests.

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

Upvotes: 0

Related Questions