when I post a Soap request with HttpBuilder, I get an exception.
My Code:
def reqxml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <web:GetWeather xmlns:web=\"http://www.webserviceX.NET\">\n" +
" <web:CityName>Berlin</web:CityName>\n" +
" <web:CountryName>Germany</web:CountryName>\n" +
" </web:GetWeather>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>"
def http = new HTTPBuilder("http://www.webservicex.com/globalweather.asmx?WSDL")
http.request(Method.POST, ContentType.XML) {
body = reqxml
response.success = { resp, xml ->
println (xml)
}
response.failure = {resp, xml ->
println "Error"
}
}
This code throws a SAXParseException with the message Content is not allowed in prolog.
Happens at the http.request method.
Related
Hi i am getting the following error when trying to run a post req. Are there any dependencies that are missing ?
Exception in thread "main" java.lang.IllegalStateException: Cannot invoke the path method because no content-type was present in the response and no default parser has been set.
You can specify a default parser using e.g.:
RestAssured.defaultParser = Parser.JSON;
String a= "80820221";
String body= "{\n" +
" \"request\": {\n" +
" \"id\": \"" + a + "\",\n" +
" \"id2\": \"800002400434\",\n" +
" \"id3\": \"\",\n" +
" \"id4\": \"WEB\"\n" +
" }\n" +
"}";
RequestSpecBuilder reqBuilder = new RequestSpecBuilder();
// Setting Base URI
reqBuilder.setBaseUri(base);
// Setting Base Path
reqBuilder.setBasePath(basePath");
reqBuilder.setContentType(ContentType.JSON);
// Getting RequestSpecification reference using builder() method
RequestSpecification reqSpec = reqBuilder.build();
Response response = RestAssured.given(reqSpec).body(body).log().all().when().post().then().log().all().extract().response();
int status = response.getStatusCode();
System.out.println(status);
**String successMessage = response.getBody().path("response.status")**;
System.out.println(successMessage);
it is giving errror in the above line
i am expecting 200 response. In postman it is giving 200 but in script it is returning 400 and unable to get the response body
i am new to rest assured. how to send the POST resquest for the below JSON?
{
"customer_id":"001",
"appointment_id":"001",
"appointment_time":"2022-10-04 00:00:00",
"submitted_time":"2022-10-04 00:00:00",
"first_name":"ethinic",
"last_name":"one",
"date_of_birth":"1910-10-10",
"email_address":"test#gmail.com",
"address_1":"24",
"address_2":"testtwo",
"postcode":"abc123",
"phone":"1234567890",
"questions":[
{
"ethnicity":"Other Ethnic Groups - Chinese"
},
{
"do_you_or_anyone_in_your_household_have_a_fever_a_new_persistent_cough_loss_of_taste_or_smell_or_any_other_symptoms_of_covid_19":"No"
},
{
"what_is_the_main_reason_for_your_appointment_with_us":"Eye health concern"
},
]
}
There are two possible ways to send POST request with the above JSON.
Create POJO/DTO object that represents the same json structure and serialize it to json using library like GSON
Send it like it is by escaping all the quotes with slash.
1
private static MyObject obj = MyObject.builder()
.title("Title")
.userId("1234")
.build();
Response response = RestAssured.given()
.header("Content-type", "application/json")
.and()
.body(Gson.toJson(obj))
.when()
.post("/posts")
2
private static String requestBody = "{\n" +
" \"title\": \"foo\",\n" +
" \"body\": \"bar\",\n" +
" \"userId\": \"1\" \n}";
Response response = RestAssured.given()
.header("Content-type", "application/json")
.and()
.body(requestBody)
.when()
.post("/posts")
I am trying to use this link to get described response:
{
"session": {
"application_id": 2,
"created_at": "2012-04-03T07:34:48Z",
"device_id": null,
"id": 743,
"nonce": 1308205278,
"token": "0e7bc95d85c0eb2bf052be3d29d3df523081e87f",
"ts": 1333438438,
"updated_at": "2012-04-03T07:34:48Z",
"user_id": null
}
}
But now it say application not found:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
Can't go ahead to test another requests. This is a shell script I used for getting curl request:
timestamp=`date +%s`
body="application_id=HIDDENAPPLICATIONIDHERE&auth_key=HIDDENAUTHKEYHERE&nonce=2342546×tamp=$timestamp"
signature=`echo -n $body | openssl sha -hmac HIDDENSECRETHERE`
body=$body"&signature="$signature
#echo $body
#echo $signature
#exit 0
curl -X POST \
-H "QuickBlox-REST-API-Version: 0.1.0" \
-d $body \
https://api.quickblox.com/session.xml
So there some info regrding this maybe I've created shell script to a wrong way:
HMAC-SHA function of the body of the request, with a key auth_secret.
Request body is formed as the sorted (sorting alphabetically, as
symbols, not as bytes) by increase the string array 'parameter=value',
separated with the symbol "&". For the parameters passed as a
user[id]=123 is used just such a line of user[id]=123
Also I've prepped a Swift project how to generate signature and get session, but still has the same error with no application found.
Any recommendation? Thanks
Please verify Application ID parameter because server return:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
For example generate signature (Java):
Random random = new Random();
String nonce = Integer.toString(random.nextInt());
long time = System.currentTimeMillis() / 1000;
String timestamp = Long.toString(time);
String signature;
String str = "application_id=" + applicationId + "&" + "auth_key=" + authKey + "&" + "nonce="
+ nonce + "&" + "timestamp=" + timestamp + "&" + "user[login]=" + adminLogin + "&" + "user[password]="
+ adminPassword;
signature = UtilsMethods.calculateHMAC_SHA(str, authSecret);
calculateHMAC_SHA:
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String calculateHMAC_SHA(String data, String key) throws SignatureException {
String result = null;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] digest = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(digest.length * 2);
String s;
for (byte b : digest) {
s = Integer.toHexString(0xFF & b);
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
}
result = sb.toString();
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
I am trying to POST an image to my grails application and I'm not having much luck.
My titanium code is:
function upload(){
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info(picMedia + " : " +message.value);
Ti.API.info('IN ERROR ' + e.error);
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e){
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST', 'http://localhost:8080/FYP/Profile/appUploader');
// send the data
xhr.send({
media: picMedia,
message: message.value,
});
}
My grails code is as follows:
def appUploader(){
println "MEDAI PARAMS: " + params.media
def f = request.getFile('media') ;
println "HERE: " + f
if (request.getFile(params.media).getOriginalFilename()) {
println "FROM APP: " + request.getFile('myFile').getOriginalFilename()
return
}
}
Im getting error from the mobile app and error on the "if" line in the web app.
What am i doing wrong?
we had the same problem in one of our apps. The difficulty is that titanium is not really able to handle binary files in that case.
We did the following:
create base64 encoded string of the image on client side
post this string to the backend
decode base64 to image again
We analyzed a lot of network traffic and in most cases titanium tries to send the file but due to javascript its alway converted into some kind of ascii and this is not usable by the server side.
I am trying to update the fixVersion of an issue via the JIRA rest api. The JIRA version is 4.4.3#663-r165197. It is the instance hosted by codehaus, not sure if that makes a difference or not.
The request looks like:
curl -u [username]:[password] -X PUT -H 'Content-type: application/json' \
-d "http://jira.codehaus.org/rest/api/latest/issue/GEOS-[id]"
{
"update":{
"fixVersions":[
{
"set":[
{
"name":"2.2-beta3"
}
]
}
]
}
}
But I get back a 405, method not allowed error. Which makes sense if I look at the rest api docs for that version [1]. They seem to indicate there is no way to update an issue in this manner. BUt if I look at the docs for the latest version [2] they seem to indicate it is possible.
So I guess the question is how do I update an issue in this manner in JIRA 4.4? Or is it not possible?
Thanks!
[1] https://developer.atlassian.com/static/rest/jira/4.4.1.html#id151460
[2] http://docs.atlassian.com/jira/REST/latest/#id165544
For 4.4 you have to use the SOAP updateIssue method. 5.0 fixed this.
Prepare Json data as below(Here java as technology i had used), and pass using put method/API.
public static String generateJson(String customFieldId, Object value,
String attribute) {
if (isBlankOrNull(attribute)) {
return "\"" + customFieldId + "\":" + "\"" + value + "\"";
} else {
return "\"" + customFieldId + "\":{\"" + attribute + "\":\"" + ""
+ value + "\"}";
}
}
public static int invokePutMethod(String auth, String url, String data) {
int statusCode = 0;
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource
.header("Authorization", "Basic " + auth)
.type("application/json").accept("application/json")
.put(ClientResponse.class, data);
statusCode = response.getStatus();
return statusCode;
} catch (Exception e) {
Constants.ERROR.info(Level.INFO, e);
// vjErrorLog.info(Level.INFO, e);
}
return statusCode;
}
attribute could be key, id, name, value etc,
In case of fix version or components, you may have one more way to prepare json data
return "\"" + customFieldId + "\":[{\"set\" :[{ \"" + attribute
+ "\" :" + "\"" + data + "\"}]}]";
and invoke put method with above json data.