I'm new to Coldfusion and can't understand why I'm having so much trouble adding a couple of headers to an http request that I'm making with cfhttp. I'm trying to write the request using cfscript, and from everything I've read I should be able to simply do:
httpService.addParam(type="header", name="Content-Type", value="application/json");
or
httpService.addParam(type="header", name="Authorization", value=local.authPasscode);
But the outgoing request doesn't seem to contain these headers. I can tell it's not working because:
I'm getting errors back in my response
I'm doing a writeDump(GetHttpRequestData()), which shows all the details of the request (and this output does not show the Authorization header at all and shows the Content-Type header as:
multipart/form-data; boundary=----WebKitFormBoundaryZs9TyOQV02N3fQop
I also seem to have difficulty adding the body of the message in a similar way so I'm thinking I'm doing something wrong with addParam(). I'm attempting that like so:
httpService.addParam(type="body", value="hello");
Again, the response I get back has a bunch of missing field errors and the output of writeDump(GetHttpRequestData()) shows a missing body.
Am I supposed to be able to use addParam() in this way?
Full code:
httpService = new http();
httpService.setMethod("POST");
httpService.setUrl(application.config.beanstream.postURL);
local.authPasscode = "Passcode " & ToBase64(application.config.beanstream.merchantid & ":" & application.config.beanstream.APIPasscode, "utf-8");
// Set headers.
httpService.addParam(type="header", name="Authorization", value=local.authPasscode);
httpService.addParam(type="header", name="Content-Type", value="application/json");
// Construct the message body.
local.body = {
"test": "hello"
};
httpService.addParam(type="body", value=SerializeJSON(local.body));
writeDump(GetHttpRequestData());
local.result = httpService.send().getPrefix();
Update:
Okay, so I changed my postURL to that of another local page and on that page I'm using GetHttpRequestData() to log the method, protocol, headers and content all out to a file. Here's what I get:
POST
HTTP/1.1
{host={www.mysite.com},user-agent={ColdFusion},connection={close},content-length={16},authorization={Passcode Mjc1ODMwMDAwOjIwMTI5NGUwMjI2MzQxMzlBZjBFMDE2RmViRjg0RDAz},content-type={application/json}}
{"test":"hello"}
So it looks to me like I am indeed correctly sending a POST to the correct URL and the headers are getting set correctly as well. My content even seems like it's there so this is starting to feel like I'm sending invalid body data to the API. Unless anybody can think of anything else to check I'm going to investigate that further.
instead of
local.body = {
"test": "hello"
};
try
local.body = {};
local.body["test"] = "hello";
then you can
SerializeJSON(local.body)
Related
this code snippet is taken from Postman. cURL taken from the postman works fine and java code generated from postman gives a 200 response for the particular call. but the response body is not there.
what should be the user agent header?
Do I need to use this postman token in my java code as well?
Do I need to add additional headers?
My Goal is to fetch some data from this GET call.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://blahblah=60041441&attributes=blah,blah,blah")
.get()
.addHeader("User-Agent", "PostmanRuntime/7.13.0")
.addHeader("Accept", "*/*")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "7af03a15-blah,364c160f-92d7-459f-b261-4993801944a7")
.addHeader("Host", "blahblah.na.blah.net:9081")
.addHeader("cookie", "someURL=1800; com.ibm.isim.lastActivity=blahblahToekn; JSESSIONID=blahblahblah:1ajblahi8; LtpaToken2=blahblahbalah")
.addHeader("accept-encoding", "gzip, deflate")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.addHeader("User-Agent", "postman")
.build();
okhttp3.Response response= client.newCall(request).execute();
System.out.println(response.body().toString());
Suppose for simple get request following will do just fine, all other details can be omitted:
Request request = new Request.Builder()
.url("http://blahblah=60041441&attributes=blah,blah,blah")
.get()
.build();
Most of the headers (like user-agent, accept-encoding etc) will be automatically added by OkHttp client, so you can safely remove those from request:
.addHeader("User-Agent", "PostmanRuntime/7.13.0")
.addHeader("Host", "blahblah.na.blah.net:9081")
.addHeader("accept-encoding", "gzip, deflate")
.addHeader("Cache-Control", "no-cache")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.addHeader("User-Agent", "postman")
Since / is a wildcard, suppose you can skip it as well.
.addHeader("Accept", "*/*")
If you endpoint requires authentication, suppose before sending this particular Get request you need to send authentication request first. To automatically handle authentication cookies you can try to add CookieJar to your client, so those can be omitted as well (assume headers names were altered somehow, btw?):
.addHeader("Postman-Token", "7af03a15-blah,364c160f-92d7-459f-b261-4993801944a7")
.addHeader("cookie", "someURL=1800; com.ibm.isim.lastActivity=blahblahToekn; JSESSIONID=blahblahblah:1ajblahi8; LtpaToken2=blahblahbalah")
You can also check answers for that question about the ways to add CookieJar.
I am new to API testing with jayway RestAssured.
my jmeter url : http://ip:8080/servelet?token=toekntext&methodname={jsontext}
above url is POST Request, i need to fire request in jayway RestAsseured.
url = http://ip:8080/servelet
Response r = given().contentType(CONTENT_TYPE).accept(CONTENT_ACCEPT).headers("user-agent", web).queryParam("token", tokentext).queryParam("methodname", jsonttext).expect().statusCode(200).when().post(url);
Is the above code correct to fire POST Request Here i am getting 500 internal server error, plz help me.
Yes that looks right given that it truly are query parameters that JMeter is sending. I suspect that it might not be since it's very unusual in my experience that include JSON (I assume jsontext is JSON) in the request path. Try switching from queryParam to formParam to see if it makes any difference.
Try restructuring your code,
FULL-URL - url/account?token=TOKEN&sync=TRUE, then you can try post request as below
given().
contentType(ContentType.JSON).body(payload).
queryParam("token", "TOKEN").
queryParam("sync", "TRUE").
when().post(url).then().
statusCode(200).extract().response();
I'm fetching a server page using Poco::Net::HTTPClientSession with an appropriate Poco::Net::HTTPRequest, which works fine. Now I get a response back, and sometimes the returned page will be gzipped.
I need to find out when that is the case, so that I may deflate if necessary. The HTTP header that should indicate this, is Content-Encoding: gzip; but there's no getContentEncoding() method in Poco::Net::HTTPResponse.
Here's a non-working snippet (because there's no resp.getContentEncoding()):
// resp is the Poco::Net::HTTPResponse object,
// sess is the Poco::Net::HTTPClientSession
std::istream &in = sess.receiveResponse(resp);
// Get the server-returned body as a string (potentially deflate)
std::ostringstream serveroutput;
if (resp.getContentEncoding() == "gzip") {
Poco::InflatingInputStream
inflater(in, Poco::InflatingStreamBuf::STREAM_GZIP);
Poco::StreamCopier::copyStream(inflater, serveroutput);
} else
Poco::StreamCopier::copyStream(in, serveroutput);
// Now we can get at the body as a string
std::string txt = serveroutput.str();
Does anyone know how to get at the raw headers, so that I can inspect the header Content-Encoding myself, or of another useful method to determine whether a server response is gzipped?
if the server set the Content-Encoding header
you could get the encoding value like the following.
resp.get("Content-Encoding")
I'm currently trying to call Amazon Product Retail Web Service in Salesforce.
As I mentioned in
Getting WSDL parse error while generating Apex code from WSDL in Salesforce
I was initially unable to generate apex stub class, but I followed the method suggested by #Ballinger and created apex class. I wrote an apex class to use that stub and to set request parameters. The class i wrote is as follows
public class AmazonProductStubNew
{
public static void getResults()
{
System.Debug(' getResults start ');
AmazonWS.AWSECommerceServicePortUS stub = new AmazonWS.AWSECommerceServicePortUS();
stub.inputHttpHeaders_x = new Map<String,String>();
stub.inputHttpHeaders_x.put('AWSAccessKeyId','MyAmazonAWSAccessKeyId');
stub.inputHttpHeaders_x.put('Timestamp','2012-11-28T12:11:30Z');
stub.inputHttpHeaders_x.put('Signature','Encrypted Secret Code');
String MarketplaceDomain = '';
String AWSAccessKeyId = 'MyAmazonAWSAccessKeyId';
String AssociateTag = '';
String XMLEscaping = '';
String Validate = '';
AmazonWS.ItemSearchRequest Shared = new AmazonWS.ItemSearchRequest();
Shared.SearchIndex = 'DVD';
AmazonWS.ItemSearchRequest[] Request = new AmazonWS.ItemSearchRequest[1];
Request[0] = new AmazonWS.ItemSearchRequest();
Request[0].Title = 'Inception';
AmazonWS.ItemSearchResponse_element response = stub.ItemSearch(MarketplaceDomain,AWSAccessKeyId,AssociateTag,XMLEscaping,Validate,Shared,Request);
AmazonWS.Items_element[] localItems = response.Items;
System.Debug(localItems[0].TotalResults);
}
}
Even though I've added HTTP headers to stub, I'm not getting it in XML Request message
XML Request is as follows
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<env:Header />
<env:Body>
<ItemSearch xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
<MarketplaceDomain>
</MarketplaceDomain>
<AWSAccessKeyId>MyAWSAccessKeyId</AWSAccessKeyId>
<AssociateTag></AssociateTag>
<XMLEscaping></XMLEscaping>
<Validate></Validate>
<Shared><SearchIndex>DVD</SearchIndex></Shared>
<Request><Title>Inception</Title>
</Request></ItemSearch>
</env:Body></env:Envelope>
Since headers are not there in SOAP Request, There is a SOAP fault asking for Signature from Amazon Server.
As you can see, I'm new to Salesforce Apex. I followed the steps in
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_web_services_wsdl2apex.htm#http_header_support
to set the headers.
Any idea on why the header isn't getting added?
P.S I added headers manually and tried in SOAP UI, I'm getting proper response.
Thanks :)
I think you're using wrong functions :) (question is indeed confusing).
SOAP (or generally HTTP) communication consists of sending headers and actual message (payload if you like). Headers are short text thingies, message is often a giant XML.
Your code is setting HTTP headers (which are used in web communication to authenticate, provide info about your browser, preferred languages, set cookies, return status codes like 404 page not found...) Please don't be offended with the "for dummies" but I realize the wikipedia article is a bit too much, this might be simpler: http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/
And what I suspect Amazon's webservice wants is just some fields inside the <env:Header>...</env:Header> tag? Just check the generated apex code for existence of subclass called "Header" (you can also search for the variable names like "Signature". This is going to be a total wild guess but I think you'll have to write something like that:
AmazonWS.AWSECommerceServicePortUS stub = new AmazonWS.AWSECommerceServicePortUS();
AmazonWS.Header h = new AmazonWS.Header();
h.AWSAccessKeyId = 'MyAmazonAWSAccessKeyId';
h.Timestamp = '2012-11-28T12:11:30Z';
h.Signature = 'Encrypted Secret Code';
stub.Header = h; // plug it into the request
// create and plug other required tags
AmazonWS.ItemSearchRequest Shared = new AmazonWS.ItemSearchRequest();
Shared.SearchIndex = 'DVD';
AmazonWS.ItemSearchRequest[] Request = new AmazonWS.ItemSearchRequest[1];
Request[0] = new AmazonWS.ItemSearchRequest();
Request[0].Title = 'Inception';
// ...
Now, to make it more confusing you might still have to use a HTTP header, there's a special one called SOAPAction. But generally speaking I believe you're after placing your data in the XML, not in http headers.
Funny enough, I've downloaded the Java example from http://aws.amazon.com/code/Product-Advertising-API/2478 and if I read it correctly they're passing the signature in the URL (endpoint), not in the XML. Probably because it's a REST GET method (if you can access that API it could save you a lot of hair pulled, SOAP is clunky).
By using Foursquare's API I'm trying to add a new venue to a list that I made. Currently I use the this call:
https://api.foursquare.com/v2/lists/MY_USER_ID/tips/?venueid=4b3bb64ff964a520627925e3&oauth_token=XXXXXXXXX
Although the venueID is correct the output I do get is:
{
meta: {
code: 400
errorType: "param_error"
errorDetail: "Value 4b3bb64ff964a520627925e3 is invalid for item id"
}
response: { }
}
What might cause this error?
In order to add a venue to an existing list, you need to make a request to:
POST https://api.foursquare.com/v2/lists/LIST_ID/additem?venueId=4b3...&oauth_token=XXXX
Let me know if that request doesn't work for you
I was getting a similar issue on a different API call. The fix for my issue was to include the HTTP header content type like this: Content-Type: application/x-www-form-urlencoded