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);
Related
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
I am Using web service in with Jquery Ajax this returning me the following string
{"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}
but when I am trying to parse this it is giving me error
var response = '{"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}';
console.log(JSON.parse(response));
As others have noted, you need to remove the quotes around the braces.
const PATTERNS = [/"(\[)/g, /(\])"/g]; // Invalid patterns
const JsonFixer = json => PATTERNS.reduce((s, re) => s.replace(re, '$1'), json);
var rawJsonResponse = '{"d":"[{\"username\":\"ABC\",\"designation\":\"\"}]"}';
console.log(JSON.parse(JsonFixer(rawJsonResponse)));
.as-console-wrapper { top: 0; max-height: 100% !important; }
I have a doubt, I need to capture a value that is in the HTML input using jsoup.
For example:
<input type = "text" id = "national" value = "3.26" style = "width: 2.3em;">
I need to capture only the value "3.26"
I tried using the command: Element mdolar = document.getElementById ("national");
but does not display any information.
What am I doing wrong?
Thank you.
The following test extracts the value from an input element with id=national.
This test passes using the HTML supplied in your question.
#Test
public void parseInputValueFromHtml() {
String html = "<input type = \"text\" id = \"national\" value = \"3.26\" style = \"width: 2.3em;\">";
Document document = Jsoup.parse(html);
Element mdolar = document.getElementById("national");
Assert.assertEquals("3.26", mdolar.attr("value"));
// you can also find this element by type:
Elements mdolars = document.select("input[id=national]");
Assert.assertEquals(1, mdolars.size());
Assert.assertEquals("3.26", mdolars.first().attr("value"));
}
I want to retrieve a value of a javascript section in a PHP file with my application in Java.
The PHP page contain something like :
<script type="text/javascript">
var tab= new Array();
tab[0] = "value0";
tab[1] = "value1";
tab[2] = "value2";
</script>
I'm using jsoup for parsing the HTML tag. I tried to use Rhino but I don't find example.
Context context = Context.enter();
Scriptable scope = context.initStandardObjects();
Object result = null;
Reader reader = new InputStreamReader(inputStreamOfThePage);
result = context.evaluateReader(scope, reader, "page", 1 , null );
Scriptable varValue = (Scriptable)scope.get("tab", scope);
String valueStr = (String)varValue .get("tab[0]", varValue );
It's giving me the exception :
java.lang.ClassCastException: org.mozilla.javascript.UniqueTag cannot be cast to org.mozilla.javascript.Scriptable
I don't know how to cast the object. Maybe there is a better way to do what I want.
Thanks
Jsoup is not suitable to parse Javascript... It's normal it doesn't work !
I have a spring controller with a request mapping as follows
#RequestMapping("/downloadSelected")
public void downloadSelected(#RequestParam String[] ids) {
// retrieve the file and write it to the http response outputstream
}
I have an html table of objects which for every row has a checkbox with the id of the object as the value. When they submit, I have a jQuery callback to serialize all ids. I want to stick those ids into an http request parameter called, "ids" so that I can grab them easily.
I figured I could do the following
var ids = $("#downloadall").serializeArray();
Then I would need to take each of the ids and add them to a request param called ids. But is there a "standard" way to do this? Like using jQuery?
I don't know about "standard way", but this is how I would do it.
var ids = $("#downloadall").serializeArray();
will give you a dataset on the form (only the checked items presented):
[{name:"foo1", value:"bar1"}, {name:"foo2", value:"bar2"}]
To feed this to jQuery's .ajax() just:
$.ajax({
url: <your url>,
data: ids.map(function (i) {return i.name+'='+i.value;}).join('&')
});
The Array.map() is not compatible with all browsers yet so you better have this code on your page too:
if (!Array.prototype.map) {
Array.prototype.map = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
This code snippet I got from mozilla developer center.
I didn't put them in a ?ids=... param, but this way they are easy to access on server side. You can always just modify the map function to fit your needs.