How to get the xml response from RestAssured Response - rest-assured

My Rest API Response is XML, how to handle the response.
My RestAPI code will be as follows:
Response res = given()
.relaxedHTTPSValidation()
.body("configtype=temperaturesysconfig")
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.post(ConfigReader.get("config.base.url") + ConfigReader.get("query.temperaturesysconfig.url"));
Response will be in res variable, i can get the response from as
res.body().toString() but it is not coming as xml, the result is as com.jayway.restassured.internal.RestAssuredResponseImpl#4390f46e.
How to get it as xml?

Try registering XML parser explicitly for the response before you make REST call as shown below.
registerParser("application/xml", Parser.XML);
Response res =
given()
.relaxedHTTPSValidation()
.body("configtype=temperaturesysconfig")
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.post(ConfigReader.get("config.base.url") +
ConfigReader.get("query.temperaturesysconfig.url"));
System.out.println(res.body().toString());

Related

How to POST the json payload data inside a telegram chat using the bot API?

I only get the text "1111" mentioned in the url as the output inside telegram chat and not the json data written inside the code.
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage? chat_id=#alerttest&text=1111"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = """
{
"stocks": "SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO"
}
""""
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
   
You are probably confused about the working of HTTP methods and Telegram API methods.
First step: Telegram sendMessage works with POST HTTP method.
It requires the text parameter, passed as GET parameter: otherwise you'll send an empty message.
This means, that if you're willing to include the JSON payload as text message you have to include your JSON attribute's values into the Telegram sendMessage text parameter, otherwise you won't be able to see that into the final message.
I found the following issues with the given code:
url contains a space.
chat_id value should be numeric. Use https://web.telegram.org/ to get the chat_id from the URL. It should be a negative number. If it's a channel or supergroup, you should prepend 100 after the minus sign.
&text=1111 should be removed from the URL, as text is specified in the body when using the requests.post() method.
data should be a dictionary containing key name text.
You can not specify "Content-Type": "application/json" in headers unless your data dictionary has been transcoded to json. This can be solved in the requests.post() call by either changing data= to json=, or by not specifying headers at all.
Working:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
resp = requests.post(url, headers=headers, json=data)
print(resp.status_code)
Working:
import requests
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
resp = requests.post(url, data=data)
print(resp.status_code)

OPTIONS 405 (Method Not Allowed) and Access to XMLHttpRequest at 'http://api..' has been blocked by CORS policy: Response to preflight request doesn't

I try to upload image using api capture with camera and then convert image in base64 and try to upload but it gives error.
public abc:string;
this.abc="/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFhUXGB8aGRYYGSEgIRo.............
sendPostRequest() {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
let postData ={
"AudometerCapture":this.abc,
"Door1":this.abc,
"Door2":this.abc,
"Door3":this.abc,
"Door4":this.abc,
"TransactionID": 27
}
this.httpClient.post('http://apiearningwheels.sharpnettechnology.com/api/DailyImageUpload/UploadDailyImages',JSON.stringify(postData),{headers:headers})
.map(res => res.json())
.subscribe(data=>{
this.showLongToast("Result is :- " + data);
console.log('result',data);
}, error => {
console.log('error',error);
this.showLongToast("Error is :- " + error);
});
}
when execute the api in postman work successfully.like this pass data as raw value then its work correctly.
for the CORS policy , the headers from the XMLHttpRequest which you are accessing to that API are in proper.
Once check the Headers in postman and your code.
And also try once without using the headers.
refer here : here

Can I can return json list from HttpClientResponse

I am trying to connect with our server using dart and flutter. I get an error in certificate server, I get the code and I get response exactly, but the problem is the response keeps coming back as a string. I want it as a list to loop through it.
HttpClient client = new HttpClient();
client.badCertificateCallback =((X509Certificate cert, String host, int port) => true);
String url ='https://xxx';
//Map map = { "email" : "email" , "password" : "password"};
HttpClientRequest request = await client.getUrl(Uri.parse(url));
//request.headers.set('content-type', 'application/json');
//request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
I have simple code to get a JSON response as a list. The problem is our server is using https and nginx to take all request to the correct port. Previous code worked but I need to respond with a list.
simple code is :
String apiURL = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(apiURL);
return json.decode(response.body);
You won't get a list. You would get flat json which you would need to process. Processing can be done using simple script using powershell.

How do I can iterate cookie values from http response?

I am using rest API in my flutter app. For further request I need JSESSIONID which I received from my profile API. I successful got response but I need guide to iterate cookie value.
I followed following steps:
final response = await http.get(
strURL,
headers: {
"Authorization": basicAuth,
"Content-Type": "application/json"
},
);
String rawCookie = response.headers['set-cookie'];
print('rawCookie $rawCookie');
As print raw cookie it is printing details:
flutter: rawCookie __cfduid=d5bbe3f8a131478a78ae996e636cca0401544177738; expires=Sat, 07-Dec-19 10:15:38 GMT; path=/; domain=.rayz.ch; HttpOnly,JSESSIONID=6AD6698C5BFC90F1D089696A955E6824; Path=/; HttpOnly
I can iterate it by substring but I want to iterate it with a proper way. So please guide me on this.
With package:http you need to split the cookie string yourself using String.split. If you want to use the underlying http client, that gives you a pre-parsed list of cookies, for example:
HttpClient _httpClient = new HttpClient();
HttpClientRequest request = await _httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
print(response.cookies); // this is a List<Cookie>
Here is my code which runs perfectly and if any key does not have value, then it shows range error. But as your doubt, this code is running fine.
var headersList = response.headers['set-cookie']!.split(";");
for(var kvPair in headersList){
var kv = kvPair.split("=");
var key = kv[0];
var value = kv[1];
if(key.contains("session_id")){
print(value);
}
}

Dart: Get POST parameters on server side

I send some data from client side using POST request
var value = new Map<String, String>();
value["param1"] = 'value1';
value["param2"] = 'value2';
value["param3"] = 'value3';
HttpRequest.postFormData('http://localhost:8080/', value);
and try to get this data on the server side:
HttpServer.bind(InternetAddress.ANY_IP_V6, 8080).then((server) {
server.listen((HttpRequest request) {
//TODO: process POST request
});
});
But how can I get POST values from the request as Map< string, string>?
upd 1
But as I see result of
var jsonString = await request.transform(UTF8.decoder).join();
depends on type of post message. If I change it result will be
multipart/form-data
------WebKitFormBoundaryoQQD7N0iA5zS8qmg
Content-Disposition: form-data; name="param1"
value 1
------WebKitFormBoundaryoQQD7N0iA5zS8qmg
Content-Disposition: form-data; name="param2"
value 2
------WebKitFormBoundaryoQQD7N0iA5zS8qmg
Content-Disposition: form-data; name="param3"
value 3
------WebKitFormBoundaryoQQD7N0iA5zS8qmg--
text/plain
param1=value 1
param2=value 2
param3=value 3
application/x-www-form-urlencoded
param1=value+1&param2=value+2&param3=value+3
As I have already asked how can I convert it to Map< string, string>?
Here is a complete tutorial https://www.dartlang.org/docs/tutorials/httpserver/#handling-post
String jsonString = await request.transform(UTF8.decoder).join();
or
Map result = await request.transform(UTF8.decoder).join().then(JSON.decode);
I have the same question, and I didn't find any solution until now. I need to pass a map from client to server, and server to use that map to interrogate a mongodb database. Client send that map, but server receive a string. Any conversion to json return also string, not a map.
On the client side I send a map named query:
await HttpRequest.postFormData('http://localhost:8085/$_coll',query).then((HttpRequest response)
On the server side :
if (request.method == 'POST') {
query = await request.transform(utf8.decoder).join();
}
I've tried to encode/decode to json, but with no success.

Resources