Extract the contents of a plain/text in rest assured - java

I am getting a response from my RestAssured call as ContentType text/plain;charset=UTF-8.
I searched the internet but am unable to find a nice way to get the content out of the message as using the below is not so nice;
String content = response.then().extract().body().htmlPath().get().children().get(0).toString();
How can I extract the contents of this response a little more nice?

You can directly use .asString() to get the body content of the response irrespective of this return Content-Type.
You can try something like that:
response.then().extract().body().asString();
or directly:
response.asString();

You can try
String ResponseAsString=given().get("http://services.groupkt.com/state/get/IND/UP").asString();
System.out.println("My ResponseAsString is:"+ResponseAsString);
Also you can extract the response using JsonPath even though it's ContentType.TEXT
Response response=given().contentType(ContentType.TEXT).get("http://localhost:3000/posts");
//we need to convert response as a String and give array index
JsonPath jsonPath = new JsonPath(response.asString());
String title = jsonPath.getString("title[2]");
String author=jsonPath.getString("author[2]");

This is the way it work to me
import io.restassured.response.Response;
response.getBody().prettyPrint();

Related

Jsoup parse response without logging to console

I have a tiny problem with Jsoup.
I am using this snippet of code
Response response = getAccount(); // GET Response in HTML format
Document document = Jsoup.parse(response.body().prettyPrint());
And it prints to console all the response, which is very messy, as response is in HTML format. I read that prettyPeek() is not logging response, but return value of prettyPeek() is not String type but Response, and even if I use prettyPeek().toString() my code doesn't work. Please tell me what snippet will work the same way as mine, but without logging to console.
To parse HTML into a Document just parse the body:
Document document = Jsoup.parse(response.body());
And that's it.
Also do you really need a reponse as a Response object?
You can get the Document by simply calling:
Document document = Jsoup.connect("http://example.com/").get();
Take a look at these very simple examples to see if there's a better way to do what you're trying to achieve:
https://jsoup.org/cookbook/input/load-document-from-url

Json Parser not working on request mapping

Problem:
I am unable to parse json request to an object containing double quotes in it.
For example:
jsonString = {
"desc":"Hello stackOverFlow, please reach on this email "asdas#gmail.com". thanks";
}
When I am trying to convert this I am not able parse to an variable, because it looks like invalid json but in real time the request has double quotes in it.
Please show me some good parsing techniques which can do parse this type of requests.
Thanks
You have to escape all of the double quotes, so for example:
String json = "\"{\"desc\":\"Hello stackOverFlow, please reach on this email \"asdas#gmail.com\". thanks\"}";
As you can see it is a lot of work to create very simple JSON, so you are better of using some library for that. I recommend you org.json, it is very lightweight and easy to use. Using it, it would look like this:
JSONObject json = new JSONObject();
json.put("description", "Your description....");
String jsonString = json.toString();

Converting JSON file to string in RestAssured (Java)

I'm using IntelliJ to learn RestAssured; this is completely new territory for me. I have a simple .json file in place and I want to have a API Response to assert if it's the same as the mentioned .json file.
Basically: If the output of the call equals what I have in the json file, it's all good.
I used the demo restapi.demoqa.com for quick reference. This is what I have right now:
#Test
public void ComparewithJSONinResources()
{
String CityResponse = ?????
RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city";
RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest.request(Method.GET, "/Hyderabad");
String responseBody = response.getBody().asString();
System.out.println(responseBody);
Assert.assertTrue(responseBody.equals(CityResponse));
response.body();
}
I have the .json file in place called CityResponse.json. For easy reference, say on the location c:/CityResponse.
Is it possible to convert the Json file to a string to assert that the API and the JSON are equal?
Comparing JSON as String will never give accurate results, as you will possibly see inconsistency in space, tabs (indentation), property (key-value pair) sequencing etc. Your best bet is to parse JSON into POJO using one of the many popular libraries (Ex. Jackson, GSON etc). And this deserialization you need for both RestAssured Http response & one you are reading from .json file, and once you have two java objects, use standard Java comparision by overriding equals method.

How to put the string in the JSON and get the value in Java

I want to get the value of String and I am trying to put the string in the JSON and get it. The format of string is "key=value&key1=value". The code I am using is:
JSONObject json = new JSONObject(String);
String value = json.get("key").toString();
That string is url encoded not json formatted.
You can use a url decoder instead. Something like http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html might work for you.
I used Patterns and Matchers and it worked perfectly. Thank you.

How to get parameters out of a url encoded string (not a URL) in java

I have a url encoded string that is returned from an API I am using. I want to do something request.getParameter("paramname") on the string. What I'm looking for is something like str.request.getParameter("paramname"). There's gotta be something like this right?
clarification the api returns something like:
name1=val1&name2=val2&name3=val3
I know i could do a split on "&" and then go through each element but that seems stupid. Please advise. Thanks!
Use URLEncodedUtils from Apache httpclient library.
API : http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html
You will have to call this method to get name value pairs:
static List<NameValuePair> parse(HttpEntity entity)
Returns a list of NameValuePairs as parsed from an HttpEntity.
See this question
One answer there:
import org.eclipse.jetty.util.*;
MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo("foo=bar&bla=blub", params, "UTF-8");
assert params.getString("foo").equals("bar");
assert params.getString("bla").equals("blub");

Categories

Resources