How to execute a HttpRequest in custom Java

0
Hi, I want to make a custom java function in which i execute a Http request, but i can't get it working. For now, i have declared the variables and want the call the public abstract com.mendix.http.HttpResponse executeHttpRequest. Can anyone provide me an example?
asked
3 answers
1

Call Core.http().executeHttpRequest​(...)

https://apidocs.mendix.com/8/runtime/com/mendix/http/Http.html

answered
0

If you just need to download data from a URL, have a look at the retrieveURL Java Action in the Community Commons module in the App Store. This doesn’t use executeHttpRequest, but may do what you need. As it’s short, I’ve attached the code it uses below, but I can’t claim any credit for it. 
Hope this helps.

	public static String retrieveURL(String url, String postdata) throws Exception {
		// Send data, appname
		URLConnection conn = new URL(url).openConnection();

		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		if (postdata != null) {
			try (
				OutputStream os = conn.getOutputStream()) {
				IOUtils.copy(new ByteArrayInputStream(postdata.getBytes(StandardCharsets.UTF_8)), os);
			}
		}

		String result;
		try (
			InputStream is = conn.getInputStream()) {
			// Get the response
			result = IOUtils.toString(is, StandardCharsets.UTF_8);
		}

		return result;
	}

 

answered
0

Alternatively, you could have a look at the REST Services module, which implements all methods.

 

Note though that you should not need to execute http requests in Java: it can all be done natively.

answered