Convert binary response to ASCII string - groovy

I use SoapUI to send a request to webservice and get response.
How could I convert this binary response convert to ASCII string with Groovy script?

What binary form takes your response? Is it byte[]? If so you can easily convert it to String with following constructor:
new String(byte[] bytes, Charset charset)
An example you can try in groovyConsole:
import java.nio.charset.Charset
byte[] response = "Some response".bytes
assert new String(response, Charset.forName("UTF-8")) == "Some response"

Related

String comparison in Python3

I have a rest api which return True, False and "". Which i receive this in my requests.content I get the type as byte. I convert them to string and then try to compare. But the last else block executes leaving behind the first and second.
import requests
headers = {'Accept': '*/*'}
response = requests.get('http://{IP}/status', headers=headers)
status = response.content
status = str(status)
print(status)
# status returns "True", "False", ""
if (status == "True"):
print ('Admin approved this request')
elif (status == "False"):
print ('Admin disapproved this request')
else:
print ('No response from admin')
Getting :- 'No response from admin'
In all the cases
Double check the format of your response. If it's in something like JSON, you'll likely need to access the actual response ("True", "False", "") as a key/value pair.
Also, you can simply use response.text to get a string using UTF-8 encoding, instead of converting response.content to a string.
https://realpython.com/python-requests/#content
response.content is an object of type bytes.
Try calling decode() on response.content instead of casting to a str type.
For example if the content of the response is encoded in utf-8 then decode using utf-8:
status = response.content.decode('utf-8')
When casting a bytes object to a str type, the resulting string will be prefixed with "b'".
This is why the last else block in the code you've supplied always executes. The variable status will always be prefixed with "b'" (ie. "b'True'", "b'False'" or "b''") and the equality comparisons will always evaluate to False.

SoapUI to get attachment from response in Groovy

I tried to use following code to get attachment from reponse as text in Groovy.
def testStep = testRunner.testCase.getTestStepByName("getData")
def response = testStep.testRequest.response
def ins = response.attachments[0].inputStream
log.info(ins);
It contains some binary information too, so it is not fully human readable, but got following in output:
java.io.ByteArrayInputStream#5eca74
It is easy to simply encode it to base64 and store it as a property value.
def ins = response.attachments[0].inputStream
String encoded = ins.bytes.encodeBase64().toString()

json() on "requests" response raises UnicodeEncodeError

I'm querying Github's Jobs API with python3, using the requests library, but running into an error parsing the response.
Library: http://docs.python-requests.org/en/latest/
Code:
import requests
import json
url = 'https://jobs.github.com/positions.json?'
response = requests.get(url)
print(response.json())
Error:
UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in
position 321: ordinal not in range(128)
Using this API in the past with Ruby, I've never run into this issue.
I also tried converting it to a dictionary but it resulted in the same errors.
There's other questions on SO about the UnicodeEncodeError (mostly re: opening files), but I'm not familiar with Python and didn't find them helpful.
First, check that the response is actually JSON. Try printing response.text and see if it looks like a valid JSON object.
Assuming it is JSON: it's very "hack"-ey, but you can replace the non ASCII characters with their escaped Unicode representation:
def escape_unicode(c):
return c.encode('ascii', 'backslashreplace').decode('ascii')
response = ...
text = response.text
escaped = re.sub(r'[^\x00-\x7F]', lambda m: escape_unicode(m.group(0)), text)
json_response = json.loads(escaped)

Converting Date to String in groovy

I want to convert def date= new Date() to string so that i could make this expression def text=data+" "+"http://hjghjghj.ge(Service) /https:jsonparces getting data from taxservice:Successfully received response and then use text as an string i have tries toString() but it wasn't helpful any better ideas?
You don't even need toString(), just using it in a String concatenation transforms it, but you have to use String + Date, not Date + String, just like in Java. So either use
def text=""+date+" "+"http://hjghjghj.ge(Service) /https:jsonparces getting data from taxservice:Successfully received response
or
def text=(data as String)+" "+"http://hjghjghj.ge(Service) /https:jsonparces getting data from taxservice:Successfully received response
or
def text=data.toString()+" "+"http://hjghjghj.ge(Service) /https:jsonparces getting data from taxservice:Successfully received response`

How do we use POST method in Python using urllib.request?

I have to make use of POST method using urllib.request in Python and have written the following code for POST method.
values = {"abcd":"efgh"}
headers = {"Content-Type": "application/json", "Authorization": "Basic"+str(authKey)}
req = urllib.request.Request(url,values,headers=headers,method='POST')
response = urllib.request.urlopen(req)
print(response.read())
I am able to make use of 'GET' and 'DELETE' but not 'POST'.Could anyone help me out in solving this?
Thanks
If you really have to use urllib.request in POST, you have to:
Encode your data using urllib.parse.urlencode()(if sending a form)
Convert encoded data to bytes
Specify Content-Type header (application/octet-stream for raw binary data, application/x-www-form-urlencoded for forms , multipart/form-data for forms containing files and application/json for JSON)
If you do all of this, your code should be like:
req=urllib.request.Request(url,
urllib.parse.urlencode(data).encode(),
headers={"Content-Type":"application/x-www-form-urlencoded"}
)
urlopen=urllib.request.urlopen(req)
response=urlopen.read()
(for forms)
or
req=urllib.request.Request(url,
json.dumps(data).encode(),
headers={"Content-Type":"application/json"}
)
urlopen=urllib.request.urlopen(req)
response=urlopen.read()
(for JSON).
Sending files is a bit more complicated.
From urllib.request's official documentation:
For an HTTP POST request method, data should be a buffer in the
standard application/x-www-form-urlencoded format. The
urllib.parse.urlencode() function takes a mapping or sequence of
2-tuples and returns an ASCII string in this format. It should be
encoded to bytes before being used as the data parameter.
Read more:
Python - make a POST request using Python 3 urllib
RFC 7578 - Returning Values from Forms: multipart/form-data
You can use the requests module for this.
import requests
...
url="https://example.com/"
print url
data = {'id':"1", 'value': 1}
r = requests.post(url, data=data)
print(r.text)
print(r.status_code, r.reason)
You can send calls without installing any additional packages.
Call this function with your input data and url. function will return the response.
from urllib import request
import json
def make_request(input_data, url):
# dict to Json, then convert to string and then to bytes
input_data = str(json.dumps(input_data)).encode('utf-8')
# Post Method is invoked if data != None
req = request.Request(url, data=input_data)
return request.urlopen(req).read().decode('utf-8')

Resources