I'm using Katalon Studio and using it to send an API request. The request is basically returning information I want to use in the HTTP Header. I can use Groovy or Java to extract this but not sure how I can do it.
I've tried create_game_response.getHeadewrFields(GameCode) in order to get the GameCode but it won't work.
Here is the code I use
WS.sendRequest(findTestObject('UserRestService/Create Game'))
WS.verifyResponseStatusCode(create_game_response, 201)
def header_text = create_game_response.getHeaderFields()
println(header_text)
def game_code = create_game_response.getHeaderFields();
String game_code_list = game_code.toString()
println(game_code_list)
And this is the response:
{GameCode=[1jwoz2qy0js], Transfer-Encoding=[chunked], null=[HTTP/1.1 201 Created]}
I'm trying to extract "1jwoz2qy0js" from the game code and use it as a string, how can I do this?
getHeaderFields() returns a Map of the headers where each header is a List. Rather than converting that to a String and attempting to parse it, just get the field you want:
Map headers = create_game_response.getHeaderFields()
List gameCodes = headers["GameCode"]
And then select the first one, if that's all there is:
assert gamesCodes[0] == "1jwoz2qy0js"
Groovy code below:
str = '{GameCode=[1jwoz2qy0js], Transfer-Encoding=[chunked], null=[HTTP/1.1 201 Created]}'
left_idx = str.indexOf('[') + 1
right_idx = str.indexOf(']')
print str.substring(left_idx,right_idx)
Output:
1jwoz2qy0js
Related
I want to store a randomized integer that has been called out in the request body and store it in test case Property so that it can be passed as a body parameter in the next request.
for example:
Request1:
id_num = randomNumeric(10)
Properties:
id_num = 1234567890
Request2:
trfered_IDNum = ${#TestCase#id_num}
The Structure looks like below,
Project
|---TestSuite
|-------TestCase
|------RestRequestTestStep1
|------RestRequestTestStep2
|------GroovyScript
Let's start with some assumptions.
RestRequestTestStep1 Response Body has below fields :
{"Resp1Field1Key":"Resp1Field1Value",
"Resp1Field2Key":"Resp1Field2Value"}
RestRequestTestStep2 Request Body has below fields :
{"Resp2Field1Key":"Resp2Field1Value",
"Resp2Field2Key":"Resp2Field2Value"}
Resp1Field1Value and Resp1Field2Value from first response will be substituted to Resp2Field1Value and Resp2Field2Value of second request.
RestRequestTestStep2 body should be as below as we will be substituting values from the testCase Property that will be set in the groovy script once first request is completed.
{
"Resp2Field1Key":"${#TestCase#Resp2Field1Value}",
"Resp2Field2Key":"${#TestCase#Resp2Field2Value}"
}
The Code..rather Script : The groovy script can be placed under the same Test Case and should do below,
import groovy.json.JsonSlurper
//Substitute with appropriate testSuiteName,testCaseName,testStepName1 and testStepName1 as per the Project Structure you have.
def testSuite = testRunner.testCase.testSuite.project.getTestSuiteByName("testSuiteName")
def testCase = testSuite.getTestCaseByName("testCaseName")
def testStep1 = testCase.getTestStepByName("testStepName1")
def testStep2 = testCase.getTestStepByName("testStepName2")
// Call the first REST Request
testStep1.run(testRunner, context)
def response = testStep1.testRequest.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(response)
//Assign it to a testCase Property to grab for second Rest Request
if (jsonSlurper.size() > 0) {
testCase.setPropertyValue("Resp1Field1Value",Resp1Field1Value)
testCase.setPropertyValue("Resp1Field2Value",Resp1Field2Value)
);
//Call the second Rest Request
testStep2.run(testRunner, context)
def response = testStep2.testRequest.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(response)
// Perform Validation/assertion as desired
Use these 2 lines in your groovy script before second request in the same test case
def id_num = (new Random().nextInt(100000000)).toString()
testRunner.testCase.setPropertyValue( "id_num", id_num )
log.info id_num
Now since you have saved the value in a testcase properties in a soap step, you can use like below in the next request within same testcase
${#TestCase#id_num}
This way it will automatically replace the value once you run. To see the values replacement in soap UI , you can see the Raw Tab
check this out below.. the value got replaced
Goal :
1. Extract csrf value from my GET request response body
2. Store extracted 'csrf' value in environment variable
3. Use it in subsequent POST request.
Found a Solution and working:
var matchSETTINGS cheerio.load(responseBody);
Extract var matchSETTINGS = text.match(var a= (.*););
This is bit complicated, but achievable using various ways. Here I'm showing you a static way, change it as per your requirement.
Postman supports cheerio library, that you can use to parse HTML responses.
var html = cheerio(responseBody);
//get script tag data
var htmlData = html[14].children[1].children[5].children[0].data;
var csrfIndex = htmlData.search(/'csrf'/i);
var dataBeforeCsrf = htmlData.slice(0, csrfIndex);
//remove content before csrf node
htmlData = htmlData.replace(dataBeforeCsrf, '');
//to make it in right format of JSON, replace single quote with double,
//remove ; and add bracket
htmlData = htmlData.replace(/'/g, '"');
htmlData = htmlData.replace(';', '');
//parse to JSON
var jsonData = JSON.parse('{' + htmlData);
//print csrf
console.log(jsonData.csrf);
I'm trying to get a value from an XML response using REST Assured, but I'm only getting empty values.
XML example:
<?xml version="1.0" ?>
<ncresponse
orderID="50143601"
STATUS="5"
SCORING="1"
SCO_CATEGORY="G">
</ncresponse>
My code:
RestAssured.useRelaxedHTTPSValidation();
Map<String, String> body = new HashMap<>();
body.put("ORDERID", orderId);
body.put("USERID", QUERY.getUser());
body.put("PSW", QUERY.getPass());
Response validation = given().proxy(host("myproxy.com").withPort(8080)
).params(body).when().get(QUERY.getUrl());
return from(validation.asString()).get("ncresponse.STATUS");
In this case, I'm trying to get the STATUS value ("5"), but all I'm getting is "" for any attribute.
Any help would be very appreciated.
You need to first convert the response to xml type and then get the value from that response.
First you need to import the following in your code:
import io.restassured.path.xml.XmlPath;
And then your code should be:
String stringResponse = validation.asString();
XmlPath xmlPath = new XmlPath(stringResponse);
String status = xmlPath.get("ncresponse.STATUS");
Now the String status contains the value which you want.
Well, i realized that I was making a mistake here. I was trying to get an attribute from the node "ncresponse", so using "#" symbol before the attribute is neccesary:
from(validation.asString()).get("ncresponse.#STATUS");
Im closing this, thanks for all!
According to Facebook Docs
If your app is making enough calls to be considered for rate limiting by our system, we return an X-App-Usage HTTP header. [...] When any of these metrics exceed 100 the app will be rate limited.
I am using Facebook4J to connect my application to the Facebook API. But I could not find any documentation about how I can get the X-App-Usage HTTP header after a Facebook call, in order to avoid being rate limited. I want to use this header to know dinamically if I need to increase or decrease the time between each API call.
So, my question is: using Facebook4J, is possible to check if Facebook returned the X-App-Usage HTTP header and get it? How?
There is a getResponseHeader method for the response of BatchRequests in facebook4j see Facebook4j code examples
You could try getResponseHeader("X-App-Usage")
// Executing "me" and "me/friends?limit=50" endpoints
BatchRequests<BatchRequest> batch = new BatchRequests<BatchRequest>();
batch.add(new BatchRequest(RequestMethod.GET, "me"));
batch.add(new BatchRequest(RequestMethod.GET, "me/friends?limit=50"));
List<BatchResponse> results = facebook.executeBatch(batch);
BatchResponse result1 = results.get(0);
BatchResponse result2 = results.get(1);
// You can get http status code or headers
int statusCode1 = result1.getStatusCode();
String contentType = result1.getResponseHeader("Content-Type");
// You can get body content via as****() method
String jsonString = result1.asString();
JSONObject jsonObject = result1.asJSONObject();
ResponseList<JSONObject> responseList = result2.asResponseList();
// You can map json to java object using DataObjectFactory#create****()
User user = DataObjectFactory.createUser(jsonString);
Friend friend1 = DataObjectFactory.createFriend(responseList.get(0).toString());
Friend friend2 = DataObjectFactory.createFriend(responseList.get(1).toString());
I'm trying to access the page http://www.betbrain.com with jsoup, but this give me error 307. Anyone knows how I can fix this?
String sURL = "http://www.betbrain.com";
Connection.Response res = Jsoup.connect(sURL).timeout(5000).ignoreHttpErrors(true).followRedirects(true).execute();
HTTP status code 307 is not an error, it's an information saying that the server is making a temporary redirect to another page.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for info about HTTP Status codes.
The response returned from your request holds the value for the redirect inside the headers.
To get the header-values you could something like this:
String[] headerValues = res.headers().values().toArray(new String[res.headers().values().size()]);
String[] headerKeys = res.headers().keySet().toArray(new String[res.headers().keySet().size()]);
for (int i = 0; i < headerValues.length; i++) {
System.out.println("Key: " + headerKeys[i] + " - value: " + headerValues[i]);
}
You need you own code of course for this, as you need your response.
Now when you look at the headers written to the console you will see a key:
Location which has a value of http://www.betbrain.com/?attempt=1.
This is your URL to redirect to, so you would do something like:
String newRedirectedUrl = res.headers("location");
Connection.Response newResponse = Jsoup.connect(newRedirectUrl).execute();
// Parse the response accordingly.
I am not sure why jsoup isn't following this redirect correctly, but it seems like it could have something to do with the standard Java implementation of HTTP redirects.