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!
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 facing an issue while making a request body to do an API call in Java.
Required Body
{
"id" : [1,2]
}
I have an integer array with me lets say arr, I am creating the request something like:-
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",Arrays.toString(arr));
String stringBody = jsonObject.toJSONString();
RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);
What it actually does is make the request body as something like below.
{
"id" : "[1,2]"
}
As it sends the value as String so my server throws an error, Expected a list of items but got type \"unicode\".
Can somebody help me in here. How do I send it in raw format instead of String.
Use
jsonObject.put("id",Arrays.asList(arr));
to build the json body.
I want to read a json sent to my controller via post.
When I do this:
System.out.println(request().body());
Result is:
DefaultRequestBody(None,None,None,None,None,Some(MultipartFormData(Map(json -> List({"a":"Test","b":"sssd"})),List(),List(),List())))
Now I will follow this documentation: https://www.playframework.com/documentation/2.5.x/JavaJsonActions
And I do this:
System.out.println(request().body().asJson());
Result is:
NULL
How can I access my json?
I also tried this:
Http.MultipartFormData multipartFormData = request().body().asMultipartFormData();
System.out.println(request().body());
System.out.println(request().body().asMultipartFormData());
System.out.println(multipartFormData.asFormUrlEncoded().get("a"));
It also returns null
Thanks to all
a possible solution is
Http.RequestBody body = request().body();
JsonNode json = body.asJson();
System.out.println(json);
Im not sure whats the error behind this, but im getting an error saying
org.json.JSONException: No value for
http://starstrakph.s3.amazonaws.com/12/avatars/1386757806.jpg
My JSON are as follows
{"id":"12","display_name":"Anne","screen_name":"Anne Curtis","avatar":"http:\/\/starstrakph.s3.amazonaws.com\/12\/avatars\/1386757806.jpg","avatar_source":"http:\/\/www.balita.com\/filipino-superstar-anne-curtis-katulong-ng-pechanga-resort-casino-sa-pagdiriwang-ng-araw-ng-kasarinlan-ng-pilipinas\/"}
And my codes are:
JSONObject userObj = new JSONObject(result);
cFeeds.SetPostScreenName(userObj.getString("screen_name"));
String avatar = userObj.getString(userObj.optString("avatar"));
cFeeds.SetAvatar(avatar);
Should I use JSON array for this? is there any wrong on my code or am i missing something?
Thanks in advance
The problem is that you are using the value of the json object (which is a json String) named avatar as the name of another json object which obviously doesn't exist.
String avatar = userObj.getString(userObj.optString("avatar"));
It seems you just want the value of avatar, so just get it
String avatar = userObj.optString("avatar");
Need a quick help. I am a newbie in QuickFixJ. I have a FIX message in a txt file. I need to convert that into FIX50SP2 format. I am enclosing the code snippet.
String fixMsg = "1128=99=25535=X49=CME34=47134052=20100318-03:21:11.36475=20120904268=2279=122=848=336683=607400107=ESU2269=1270=140575271=152273=121014000336=2346=521023=1279=122=848=336683=607401107=ESU2269=1270=140600271=206273=121014000336=2346=681023=210=159";
System.out.println("FixMsg String:"+fixMsg);
Message FIXMessage = new Message();
DataDictionary dd = new DataDictionary("FIX50SP2.xml");
FIXMessage.fromString(fixMsg, dd, false);
System.out.println("FIXMessage Output:" + FIXMessage.toString()); // Print message after parsing
MsgType msgType = new MsgType();
System.out.println(FIXMessage.getField(msgType));
Here is the output:
FixMsg String:1128=99=15835=X49=CME34=47164052=2012090312102051175=20120904268=1279=122=848=336683=607745107=ESU2269=1270=140575271=123273=121020000336=2346=501023=110=205
FIXMessage Output:9=6135=X34=47164049=CME52=2012090312102051175=20120904268=110=117
quickfix.FieldNotFound: Field [35] was not found in message.
at quickfix.FieldMap.getField(FieldMap.java:216)
at quickfix.FieldMap.getFieldInternal(FieldMap.java:353)
at quickfix.FieldMap.getField(FieldMap.java:349)
at MainApp.main(MainApp.java:52)
I want to extract MsgType field (field 35). Could you please tell me where I am wrong? The thing I have observed is that after parsing to FIX50SP2 format, the convert FIX message is missing many data element (for details see the output)
Thanks
Like others mentioned the MsgType is an header field and you get it by using the following
String msgType = null;
if(FIXMessage.getHeader().isSetField(MsgType.FIELD)) {
msgType = FIXMessage.getHeader().getString(MsgType.FIELD);
}
System.out.println("MsgType is " + msgType);`
The reason you are missing many data element after parsing is, probably your message have some custom tags(like tag 2346), which is not defined in your data dictionary(FIXSP02.xml). hence the parsing of those tags failed and missing in the output.
To fix this, get the data dictionary from the party that is sending you the message and use it to parse the message
I'm not familiar with FIX messages and QuickFixJ, but glancing at the Javadoc, it seems like you should use the identifyType method :
String fixMsg = "1128=99=25535=X49=CME34=47134052=20100318-03:21:11.36475=20120904268=2279=122=848=336683=607400107=ESU2269=1270=140575271=152273=121014000336=2346=521023=1279=122=848=336683=607401107=ESU2269=1270=140600271=206273=121014000336=2346=681023=210=159";
MsgType msgType = Message.identifyType(fixMsg);
You may find FixB framework useful as it deals well with non-standard use cases of FIX.
As in your case, to extract only data you are interested in, you need to define a class that will represent this data and to bind it to FIX using annotations. E.g.:
#FixBlock
public class MDEntry {
#FixField(tag=269) public int entryType; // you could define an enum type for it as well
#FixField(tag=278) public String entryId;
#FixField(tag=55) public String symbol;
}
...
FixFieldExtractor fixExtractor = new NativeFixFieldExtractor();
List<MDEntry> mdEntries = fixExtractor.getGroups(fixMsg, List.class, 268, FixMetaScanner.scanClass(MDEntry.class))
In more common cases, FixSerializer interface should be used, but it requires a message with MsgType(35) tag and a class annotated with #FixMessage(type="...") accordingly. E.g.:
#FixMessage(type="X")
public class MarketData {
#FixGroup(tag=268) public List<MDEntry> entries;
}
...
FixMetaDictionary fixMetaDictionary = FixMetaScanner.scanClassesIn("my.fix.classes.package");
FixSerializer fixSerializer = new NativeFixSerializer("FIX.5.0.SP2", fixMetaDictionary);
MarketData marketData = fixSerializer.deserialize(fixMsg);
I hope you will find it useful.
If you need just a MsgTyp, you're sure the message is correct and you do not need any other field from the message, then I would recommend extracting MsgType from string using regexp.
e.g.: \u000135=(\w+)\u0001
It is MUCH FASTER than parsing (and validating) a string via QuickFix.