Retrieving a file via URL from a Java action

1
I'm creating a Java email handler - using the commons library from Apache - to embed images in emails. Unfortunately, requesting an image from Java results in a 401 authentication error (using an URL like http://localhost//file?fileID=123456), but I am able to open the image via the same URL from a browser. Does anyone have a clue what could be going on? Any help is very much appreciated.
asked
2 answers
4

I guess you are logged in (cookies are set) in that browser?

The Mendix framework requires you to log in, especially when entity access is configured and anonymous access do not have access to it. If you'd want to retrieve files in Java you'd have to log in and use a cookie in your requests too.

For logging in you would need to post to the url of the application and add /xas/, for example http://localhost:8080/xas/

Here's a piece of code that I wrote once for logging in through Java:

    public void login() throws IOException, RunFailedException
{
    PostMethod post = new PostMethod(this.url.toString());
    RequestEntity entity;
    String password = getPassword();
    String username = getUsername();
    if (password != null) //not anonymous
        entity = new StringRequestEntity("{\"action\":\"login\",\"params\":{\"username\":\""+getUsername()+"\",\"password\":\"" + password + "\"}}", null, null);
    else
        entity = new StringRequestEntity("{\"action\":\"get_current_user\",\"params\":{\"timezoneoffset\":-120}}", null, null);
    post.setRequestEntity(entity);
    post.setRequestHeader("Accept-Encoding", "gzip");

    client.executeMethod(post);

    for (Header h : post.getResponseHeaders("Set-Cookie")) 
    {
        String cookieValue = h.getValue();
        if (cookieValue.indexOf("XASSESSIONID") > -1)
        {
            int indexOfIs = cookieValue.indexOf("=");
            int indexOfSemiColon = cookieValue.indexOf(";");
            if (indexOfIs > -1 && indexOfSemiColon > -1)
                xasSessionID = cookieValue.substring(indexOfIs+1, indexOfSemiColon);
            else
                throw new RunFailedException("Unable to read cookie");
        }
    }

    if (post.getStatusCode() != 200)
        throw new RunFailedException("Failed to login user " + (username != null ? username : ""));
}

And some for actually using that cookie in a request:

public String[] doRequest(String content) throws IOException
{
    String[] returnArray = new String[2];
    RequestEntity requestEntity = new StringRequestEntity(content, null, null);

    PostMethod post = new PostMethod(this.url.toString());
    post.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    post.setRequestHeader("Cookie", "XASSESSIONID=" + xasSessionID);
    post.setRequestHeader("X-Mx-ReqToken", UUID.randomUUID().toString());
    // try gzip
    post.setRequestHeader("Accept-Encoding", "gzip");

    post.setRequestEntity(requestEntity);
    client.executeMethod(post);

    InputStream responseBodyStream = post.getResponseBodyAsStream();
    Header contentEncodingHeader = post.getResponseHeader("Content-Encoding");
    if (contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip"))
        responseBodyStream = new GZIPInputStream(responseBodyStream);
    String response = IOUtils.toString(responseBodyStream);

    Integer statusCode = post.getStatusCode();
    post.releaseConnection();   //is this needed? http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpMethodBase.html#releaseConnection%28%29 suggests it will be closed anyway when response is read


    returnArray[0] = statusCode.toString();
    returnArray[1] = response;
    return returnArray;
}

This is for a somewhat old version of Apache HttpClient, I don't think StringRequestEntity still works, but you'll get the gist of it. The request is for doing a POST btw, you will have to rewrite it for a GET anyway.

answered
0

As an alternative you can write a custom requesthandler that provides the images. See deeplink module in the appstore for a start.

answered