简体   繁体   中英

Mirth HTTP POST request with Parameters using Javascript

The following code by @Nick Rupley works well, but, I need also to pass parameters as POST. How do we pass POST parameters? from java.net.URL

var url = new java.net.URL('http://localhost/myphpscript.php');
var conn = url.openConnection();
var is = conn.getInputStream();
try {
    var result = org.apache.commons.io.IOUtils.toString(is, 'UTF-8');
} finally {
    is.close();
}

2 Parameters to pass: firstname="John" and lastname="Smith"

Thanks

This will POST with MIME type application/x-www-form-urlencoded . It is using apache httpclient, which is already included with mirth, as it is used internally by the HTTP Sender connector, as well as some other functionality. Other solutions may require you to download jars and add library resources.

Closer is part of Google Guava, which is also already included with mirth.

Check comments where Rhino javascript allows for simplified code compared to direct Java conversion.

It wouldn't be a bad idea to wrap all of this up in a code template function.

var result;

// Using block level Java class imports
with (JavaImporter(
    org.apache.commons.io.IOUtils,
    org.apache.http.client.methods.HttpPost,
    org.apache.http.client.entity.UrlEncodedFormEntity,
    org.apache.http.impl.client.HttpClients,
    org.apache.http.message.BasicNameValuePair,
    com.google.common.io.Closer))
{
    var closer = Closer.create();
    try {
        var httpclient = closer.register(HttpClients.createDefault());
        var httpPost = new HttpPost('http://localhost:9919/myphpscript.php');
        // javascript array as java List
        var postParameters = [
            new BasicNameValuePair("firstname", "John"),
            new BasicNameValuePair("lastname", "Smith")
        ];

        // Rhino JavaBean access to set property
        // Same as httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
        httpPost.entity = new UrlEncodedFormEntity(postParameters, "UTF-8");

        var response = closer.register(httpclient.execute(httpPost));
        // Rhino JavaBean access to get properties
        // Same as var is = response.getEntity().getContent();
        var is = closer.register(response.entity.content);
        result = IOUtils.toString(is, 'UTF-8');
    } finally {
        closer.close();
    }
}
logger.info(result);

Following is a complete working HTTP POST request solution tested in Mirth 3.9.1

importPackage(Packages.org.apache.http.client);
importPackage(Packages.org.apache.http.client.methods);
importPackage(Packages.org.apache.http.impl.client);
importPackage(Packages.org.apache.http.message);
importPackage(Packages.org.apache.http.client.entity);
importPackage(Packages.org.apache.http.entity);
importPackage(Packages.org.apache.http.util);

var httpclient = HttpClients.createDefault();

var httpPost = new HttpPost("http://localhost/test/"); 
var httpGet = new HttpGet("http://httpbin.org/get");

// FIll in each of the fields below by entering your values between the ""'s
var authJSON = {
    "userName": "username",
    "password": "password",
};

var contentStr =JSON.stringify(authJSON);
//logger.info("JSON String: "+contentStr);


httpPost.setEntity(new StringEntity(contentStr,ContentType.APPLICATION_JSON,"UTF-8"));
httpPost.setHeader('Content-Type', 'application/json');
httpPost.setHeader("Accept", "application/json");


// Execute the HTTP POST
var resp;
try {
    // Get the response
    resp = httpclient.execute(httpPost);
    var statusCode = resp.getStatusLine().getStatusCode();
    var entity = resp.getEntity();
    var responseString = EntityUtils.toString(entity, "UTF-8");
    var authHeader = resp.getFirstHeader("Authorization");
    
//  logger.info("Key : " + authHeader.getName()+" ,Value : " + authHeader.getValue());
    
    
    // Save off the response and status code to Channel Maps for any potential troubleshooting
    channelMap.put("responseString", responseString);
    channelMap.put("statusCode", statusCode);
    
    // Parse the JSON response
    var responseJson = JSON.parse(responseString);
    

    // If an error is returned, manually throw an exception
    //  Else save the token to a channel map for use later in the processing
    if (statusCode >= 300) {
        throw(responseString);
    } else {
        logger.info("Token: "+ authHeader.getValue());
        channelMap.put("token", authHeader.getValue());
    }
} catch (err) {
    logger.debug(err)
    throw(err);
} finally {
    resp.close();
}

This linke + above answers helped me to come up with a solution https://help.datica.com/hc/en-us/articles/115005322946-Advanced-Mirth-Functionality

There are plenty of libraries that can help you with URI building in Java. You can find them below. But if you want to stay in Javascript just add your parameters manually than create it.

function addParam(uri, appendQuery) {
    if (appendQuery != null) {
        uri += "?" + appendQuery;
    }
    return uri;
}

var newUri = addParam('http://localhost/myphpscript.php', 'firstname="John"');
var url = new java.net.URL(newUri);

Java EE 7

import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();

org.apache.httpcomponents:httpclient:4.5.2

import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();

org.springframework:spring-web:4.2.5.RELEASE

import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();

There are multiple ways to provide http client connection with java. Since your question is specific to java.net.URL I will stick to that.

Basically you can pass parameters as POST, GET, PUT, DELETE using .setRequestMethod this will be used along with new java.net.URL(ur-destination-url).openConnection();

Here is the complete code I've using javascript in Mirth using the same java.net.URL use this it will be helpful. It worked well for me.

do {
try {
// Assuming your writing this in the destination Javascript writer
var data = connectorMessage.getEncodedData();
//Destination URL
destURL = “https://Your-api-that-needs-to-be-connected.com”;
//URL
var url = new java.net.URL(destURL);
var conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
enter code here
conn.setRequestProperty (“Authorization”, globalMap.get(‘UniversalToken’));
conn.setRequestMethod(“DELETE”); // this can be post or put or get or patch
conn.setRequestProperty(“Content-length”, data.length());
conn.setRequestProperty(“Content-type”, “application/json”);
var outStream = conn.getOutputStream();
var outWriter = new java.io.OutputStreamWriter(outStream);
outWriter.write(data);
outWriter.close();
// Get response Code (200, 500 etc.)
var respCode = conn.getResponseCode();
if (respCode != 200) {
// Write error to error folder
var stringData = response.toString() + “\n”;
FileUtil.write(“C:/Outbox/Errors/” + $(“originalFilename”) + “.ERROR_RESPONSE”, false, stringData);
// Return Error to Mirth to move the file to the error folder
return ERROR;
}
errorCond = “false”;
break;
}
catch(err) {
channelMap.put(“RESPONSE”, err);
responseMap.put(“WEBSVC”, ResponseFactory.getErrorResponse(err))
throw(err);
// Can return ERROR, QUEUED, SENT
// This re-queues the message on a fatal error. I”m doing this since any fatal message may be
// caused by HTTPS connect errors etc. The message will be re-queued
return QUEUED; // Re-queue the message
java.lang.Thread.sleep(6000); // 6 seconds * 10
errorCond = “true”;
}
}
while (errorCond == “true”);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM