Scala ByteArrayInputStream to String - string

I'm trying to log the body of a post made using org.apache.http.client. I'm using Scalatra version 2.4.0.RC3 and Scala version 2.11.7. My response is a 400 Bad Request and I need to get the message provided in the response body.
Here is my current code:
val response = client.execute(post)
println(response)
println(response.getEntity().getContent())
response.getEntity().getContent() prints:
java.io.ByteArrayInputStream#1q232e4e
I need to get the actual body as string from this ByteArrayInputStream.

You can use EntityUtils form the same library:
import org.apache.http.util.EntityUtils;
println(EntityUtils.toString(response.getEntity()));

Related

How to get raw response data from axios request?

I am making a request to an API in which they sign their response body with a private key and send me the signature in a header. I am supposed to use their public key to validate the signature with the original response body but at the moment axios parses the response data there is something that is changing in it which makes the signature invalid. Is there some way to get the raw response data with axios?
I am doing a post request and want to get the string of the JSON object that axios automatically parses for me.
You can set a "identity" transformResponse.
let res = axios.get("url",
{ transformResponse: (r) => r }); //null transform (we do not want to parse as JSON);
//res.data should now contain a plain unparsed string
Not sure if setting transformResponse to null does the same thing as the identity transform.

Errors when trying NetSuite's Restlet interface: datain is null

I'm trying out Restlets for the first time and I am having trouble returning any data.
I've built a basic restlet and deployed it in NetSuite. The code is as follows:
function getRESTlet(dataIn) {
return nlapiLoadRecord(dataIn.recordtype, dataIn.id); // e.g recordtype="customer", id="769"
}
Using Chromes' REST Console application I've set up the following:
Request URI: https://rest.netsuite.com/app/site/hosting/restlet.nl?script=123&deploy=1&recordtype=customer&id=2409
Request Headers: NLAuth nlauth_account=123456,nlauth_email=email#emailaddy.com,nlauth_signature=password
Running it as a GET operation I return the following error:
error code: JS_EXCEPTION
error message:type
Followed by the following email:
Date & Time: 8/19/2013 2:48 pm
Execution Time: 0.06s
Script Usage: 0
Script: getRecord
Type: RESTlet
Function: getRESTlet
Error: SSS_MISSING_REQD_ARGUMENT
type
Stack Trace: getRESTlet(getCustomer.js:14)
restletwrapper(null$lib:3)
The customer record exists, the RestLet code is from the NetSuite help system, and I get an error email when the script fails so I know the deployment URL is good.
Any ideas on what I'm doing wrong?
--EDIT--
Changing my function signature to function getRESTlet(type,dataIn) resolves the type error, although now I get:
error code: UNEXPECTED_ERROR
error message:TypeError: Cannot read property "recordtype" from undefined (getCustomer.js#14)
I've also removed customer and id from the request URI and instead listed them in the Request Payload section of REST Console.
--Edit 2--
adding nlapiLogExecution('DEBUG', 'JSON.stringify(datain) is:', JSON.stringify(datain)); to the function is returning blank for the log entry. It appears that datain is null....
I had a similar issue that was resolved once I set the request header content-type to application/json.
The default content-type is text/plain which passes a stringified JSON object to the function and expects a string to be returned.
If you set the content-type to application/json or application/xml the 'datain' parameter will come in as a javascript object.
From the NetSuite Docs:
If users specify a content type other than JSON or TEXT, a 415 error
is returned with the following message:
Invalid content type. You can
only use application/json, application/xml or text/plain with
RESTlets.
If users provide data in a format different from specified
type, the following error is returned with one of the following
messages:
Error code = INVALID_RETURN_DATA_FORMAT Error message =
Invalid data format. You should return TEXT. Error message = Invalid
data format. You should return a JavaScript object.
To fix the error of
Error code = INVALID_RETURN_DATA_FORMAT Error message =
Invalid data format. You should return TEXT. Error message = Invalid
data format. You should return a JavaScript object.
You can supply a Content-type to the get specified get request of 'json'. Documentation would seem to indicate that you should specify "accepts" json, but for me only the content-type on a get made the request work.
I got this error: SSS_MISSING_REQD_ARGUMENT when trying to submit a transform record type that I had specified in camel case rather that all lower case... took me a day to work that out :(
changing the function to:
function getRESTlet(datain) {
return nlapiLoadRecord(datain.recordtype, datain.id); // e.g recordtype="customer", id="769"
}
resolves the issue. I thought I had tried without camelCase, but alas I did not.
So moral of the story is: datain is case sensitive!

How to return only status code in POST request in servicestack Instead of HTML page

have created REST service using servicestack and in post request I have return object in following way
return new HttpResult(request)
{
StatusCode = HttpStatusCode.Created,
};
request: object which i have posted in database
When i check it in fiddler it render whole HTML Page of servicestack in response body, instead of that i would like to return Status code only, so please tell me how can i do?
Thanks
There was a bug in versions before < v3.05 that did not respect the HttpResult ContentType in some scenarios, it should be fixed now with the latest version of ServiceStack on NuGet or available from:
https://github.com/ServiceStack/ServiceStack/downloads
Prior to this you can still force the desired ContentType by changing the Accept:application/json Request Header on HttpClient or by appending ?format=json on the querystring of your url.
So now if you don't want to have any DTO serialized, you don't add it to the HttpResult:
return new HttpResult() { StatusCode = HttpStatusCode.Created };
Note you still might get an empty Html response back if calling this service in the browser (or any Rest Client that Accepts:text/html). You can force a ContentType that won't output any response if it has empty payload (e.g JSON/JSV) by specifying it in the result as well, e.g;
return new HttpResult() {
StatusCode = HttpStatusCode.Created,
ContentType = ContentType.Json
};

How do you assert a String in Capybara?

I am testing an API call to the server using Cucumber + Capybara with Selenium WebDriver.
I managed to get the response obj, but how do you assert that the response body contains
certain String? For example if the response body contains "Hello World" I want to assert that
this response body (Which is string) contains a pattern "World"
ex. Something like:
response = http.request(request)
response.body.should
have_text("World")
Alternatively is there a way to get "application/json" from the response and assert the contents using
Capybara?
Thanks!
I think what your looking for is have_content.
response.body.should have_content("World")
For more info, check out the README: Check out the documentation: https://github.com/jnicklas/capybara

Handling 'chunked' encoded response with HTTPBuilder/Groovy

I'm new to using groovy and have started to use it to test some REST services. I'm having an issue parsing my XML response from our service due to 'Content not allowed in prolog.' After awhile searching I came across a post saying there might be a Byte Order Marker at the beginning. To compensate I followed their approach to trim the characters before the first < and then parse the response. While this works, I was also told the issue is that the response is coming back as 'Transfer-Encoding: chunked'.
Using HTTPBuilder, is there a way to handle chunked responses without trimming characters off?
If I try:
def http = new HTTPBuilder('url')
http.request( Method.valueOf("GET"), XML )
I get the 'Content not allowed in prolog message. However:
http.request( Method.valueOf("GET"), TEXT )
Works, but requires trimming the text until the first < before sending the response to XmlParser.
I had the same issue when I needed to interact with an IIS server. The XML returned had a bogus character in front of the actual XML returned by the web server. I worked around it like this:
StringReader reader = builder.get( path: 'rcserver/systeminfo.xml', contentType: ContentType.TEXT )
def text = reader.getText()
def xml = new XmlSlurper().parseText(text.substring(1));
The HTTPBuilder class has a setContentEncoding() method that allows you to specify the response's content-type.
Maybe something like:
http.contentEncoding = ContentEncoding.Type.GZIP
http.request( Method.GET, XML)
Hope this helps.
I was having this problem as well hitting an IIS server over https. Here is a little addition to Wim Deblauwe's answer for a POST request. You have to send a different type in the request than you expect in the response.
Send a POST with XML as the request type and TEXT as the response type. Then, parse the text response into XML. This worked for me.
In Groovy:
def reader = http.request(Method.POST, ContentType.TEXT){
uri.path = "myPath.api"
send ContentType.XML, postBodyXml
}
def text = reader.getText()
def resultxml = new XmlSlurper().parseText(text.substring(1));

Resources