gpt4 book ai didi

java - 如何使用 Java 上的 Selenium WebDriver 从 json 调用(Post、Get、JSON)中获取任何值?

转载 作者:行者123 更新时间:2023-12-01 12:51:40 25 4
gpt4 key购买 nike

我有以下功能:我通过用户表单创建一个新用户。在我提交输入的数据后,创建的用户获取条形码,该条形码将用于通过手动扫描仪扫描该条形码来访问其他系统部分。那么我怎样才能通过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 - 如何使用 Java 上的 Selenium WebDriver 从 json 调用(Post、Get、JSON)中获取任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24184225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com