I'm trying to execute a simple HTTP request:
#Grab(group='io.github.http-builder-ng', module='http-builder-ng-apache', version='1.0.4')
import groovyx.net.http.*
HttpBuilder http = HttpBuilder.configure {
request.uri = 'https://stackoverflow.com'
request.accept = ['text/html']
}
http.get {
response.success { FromServer fromServer ->
println("Got status $fromServer.statusCode $fromServer.message")
println("Has body: $fromServer.hasBody")
try {
List<String> bodyLines = fromServer.reader.withReader { it.readLines() }
String body = bodyLines.join("\n")
if (body.empty) {
println("Body is empty.")
} else {
println("Body: $body")
}
} catch (Exception e) {
println("Reading successful response failed. $e")
}
}
}
The output is:
Got status 200 OK
Has body: true
Body is empty.
What's the secret to reading the response body? Groovy 2.5.19.
The response.success handler takes a BiFunction<FromServer,Object> as well where the second parameter is the body content object. If you add a second parameter to your success closure it should have the body content in it, e.g.
response.success { FromServer fromServer, Object body ->
// your stuff
}
Related
I am new to spring webclient and i'm trying to write test case for failure case for onstatus method.
Logic here
private Function<ClientResponse, Mono<? extends Throwable>> errorStrategy() {
return response -> {
return response.bodyToMono(Errors.class).flatMap(errorResponse -> {
log.info("Track Error ----> {}", errorResponse.getErrorCode());
Errors errors = new Errors(errorResponse.getErrorMsg());
return Mono.error(errors);
});
};
}
public Mono<EnterpriseSearchResponse> getCustomerID(EnterpriseSearchRequest searchRequest) {
Mono<EnterpriseSearchResponse> response = this.client.method(HttpMethod.GET)
.uri(enterpriseSearchURI + enterpriseSearchContext)
.header("Authorization", "Bearer " + enterpriseSearchAuthToken)
.accept(new MediaType[] { MediaType.APPLICATION_JSON }).bodyValue(searchRequest).retrieve()
.onStatus(HttpStatus::is5xxServerError, errorStrategy())
.onStatus(HttpStatus::is4xxClientError, errorStrategy()).bodyToMono(EnterpriseSearchResponse.class);
return response;
}
I want to write test case for errorStategy method.
can someone suggest how to achieve that?
I have the following code snipet
class **ResultToken** {
String token
String expiration
}
// HTTP post request to retrive active token
// Return : ResultToken object
ResultToken getToken(){
ResultToken token
http.request(POST) {
...
response.success = { resp, json ->
token = new ResultToken(token: json["access_token"].toString(),
expiration: json["expires_in"].toString())
}
}
token
}
def tokenValue =getToken().token
return tokenValue
Exception error :
groovy.lang.MissingPropertyException: No such property: http for class: Script259
at Script259.getToken(Script259.groovy:21)
at Script259.run(Script259.groovy:41)
Any idea?
regards
This way you define the handler which doesn't return anything usefull.
It should rather be:
ResultToken getToken(){
ResultToken token
http.request(POST) {
....
response.success = { resp, json ->
token = new ResultToken(token: json.access_token, expiration: json.expires_in)
}
}
token
}
So I got this gradle script that let's me upload apks to Nexus. The issue is that those files end up without file extension on the server which is a problem if you want to download an app from there.
It seems that I'm passing the proper mime type but even with that I'm still getting a file without extension.
Here is the code:
def uploadToRepository(File file,
String folder,
String url,
String userName,
String password){
HTTPBuilder http = new HTTPBuilder(url)
String basicAuthString = "Basic " + "${userName}:${password}".bytes.encodeBase64().toString()
http.client.addRequestInterceptor(new HttpRequestInterceptor() {
void process(HttpRequest httpRequest, HttpContext httpContext) {
httpRequest.addHeader('Authorization', basicAuthString)
}
})
try {
http.request(Method.POST, "application/vnd.android.package-archive") { req ->
uri.path = "/content/repositories/releases/${folder}"
MultipartEntity entity = new MultipartEntity()
def fileBody = new FileBody(file, "application/vnd.android.package-archive")
entity.addPart("file", fileBody)
req.entity = entity
response.success = { resp, reader ->
if(resp.status == 201) {
println "File ${file.name} uploaded"
}
}
}
} catch (Exception e) {
e.printStackTrace()
}
}
I'm trying to create a central function for dynamic web requests.
function makeWebRequest(remoteURL, requestString, callBackFunction) {
var myWebRequest = new SMF.Net.WebClient({
url : remoteURL,
httpMethod : "POST",
requestString : requestString,
requestHeaders : [
"Content-Type: application/x-www-form-urlencoded"],
onSyndicationSuccess : callBackFunction,
onServerError : function (e) {
alert(e);
}
});
myWebRequest.run(false);
}
While calling makeWebRequest, passing a callBackFunction to it like;
var remoteURL = "http://parse.com/12/test";
var requestString = "category=news&type=world";
function callBackFunction(e) {
responseText = this.responseText;
if (responseText != null) {
parsedJSON = JSON.parse(responseText);
}
}
makeWebRequest(remoteURL,requestString,callBackFunction);
Application raises an error at line
responseText = this.responseText;
How can I pass myWebRequest itself to a function like that?
I used your codeLines. I just add a textButton to Page1, and it works fine both for Android and iOS .
In Global.js;
function makeWebRequest(remoteURL, requestString, callBackFunction) {
var myWebRequest = new SMF.Net.WebClient({
url : remoteURL,
httpMethod : "POST",
requestString : requestString,
requestHeaders : [
"Content-Type: application/x-www-form-urlencoded"],
onSyndicationSuccess : callBackFunction,
onServerError : function (e) {
alert(e);
}
});
myWebRequest.run(false);
}
var remoteURL = "http://parse.com/12/test";
var requestString = "category=news&type=world";
function callBackFunction(e) {
var responseText = this.responseText;
alert(responseText);
if (responseText != null) {
parsedJSON = JSON.parse(responseText);
}
}
function Global_Events_OnStart(e) {
changeLang(Device.language, true);
include("BC.js"); //included for future BC support. Removing is not advised.
// Comment following block for navigationbar/actionbar sample. Read the JS code file for usage.
// Also there is a part of code block in Page1, which should be copied to every page for HeaderBar usage
load("HeaderBar.js");
header = new HeaderBar();
// Uncomment following block for menu sample. Read the JS code file for usage.
/*
load("Menu.js");
/**/
}
function Global_Events_OnError(e) {
switch (e.type) {
case "Server Error":
case "Size Overflow":
alert(lang.networkError);
break;
default:
SES.Analytics.eventLog("error", JSON.stringify(e));
//change the following code for desired generic error messsage
alert({
title : lang.applicationError,
message : e.message + "\n\n*" + e.sourceURL + "\n*" + e.line + "\n*" + e.stack
});
break;
}
}
In Page1.js;
function Page1_Self_OnKeyPress(e) {
if (e.keyCode === 4) {
Application.exit();
}
}
function Page1_Self_OnShow() {
//Comment following block for removing navigationbar/actionbar sample
//Copy this code block to every page onShow
header.init(this);
header.setTitle("Page1");
header.setRightItem("RItem");
header.setLeftItem();
/**/
}
function Page1_TextButton1_OnPressed(e){
makeWebRequest(remoteURL,requestString,callBackFunction);
}
it works fine. Check your makeWebRequest function, must be on Global.js. Also define "responseText" variable with "var".
I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text