繁体   English   中英

Mirth HTTP POST 请求,参数使用 Javascript

[英]Mirth HTTP POST request with Parameters using Javascript

@Nick Rupley 的以下代码运行良好,但是,我还需要将参数作为 POST 传递。 我们如何传递 POST 参数? 来自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 个要传递的参数:firstname="John" 和 lastname="Smith"

谢谢

这将使用 MIME 类型application/x-www-form-urlencoded 它正在使用 apache httpclient,它已经包含在 mirth 中,因为它由 HTTP Sender 连接器内部使用,以及其他一些功能。 其他解决方案可能需要您下载 jars 并添加库资源。

Closer 是 Google Guava 的一部分,它也已经包含在 mirth 中。

检查注释,与直接 Java 转换相比,Rhino javascript 允许简化代码。

将所有这些都包含在代码模板 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);

以下是在 Mirth 3.9.1 中测试的完整工作 HTTP POST 请求解决方案

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();
}

这个链接+上面的答案帮助我想出了一个解决方案https://help.datica.com/hc/en-us/articles/115005322946-Advanced-Mirth-Functionality

在 Java 中有很多库可以帮助您构建 URI。 你可以在下面找到它们。 但是,如果您想留在 Javascript 中,只需手动添加参数而不是创建它。

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();

有多种方法可以提供 http 客户端与 java 的连接。 由于您的问题特定于 java.net.URL 我会坚持这一点。

基本上,您可以使用.setRequestMethod将参数作为 POST、GET、PUT、DELETE 传递,这将与new java.net.URL(ur-destination-url).openConnection();一起使用。

这是我在 Mirth 中使用相同的 java.net.URL 使用 javascript 的完整代码,使用它会有所帮助。 它对我来说效果很好。

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”);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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