简体   繁体   English

将Perl代码发布到Servlet-转换为Java?

[英]Perl code to post to servlet - translate to Java?

I have the following code in Perl which posts to my HTTP Servlet, calling an API with some XML data. 我在Perl中有以下代码,该代码发布到我的HTTP Servlet中,并使用一些XML数据调用API。

my $my_hash = {
'env.adapterName' => "DefaultAdapter",
'env.systemName'  => "DefaultSystem",
'env.userId' => "admin",
'env.progId' => "PerlHttpTest",
InteropApiName => $apiName,
InteropApiData  => $xmlData
};

my $res = $ua->request(POST  'http://hostname/interop/InteropHttpServlet', $my_hash);

I would like to do this in Java but I am struggling. 我想用Java做到这一点,但是我很挣扎。 Could someone please point me in the right direction? 有人可以指点我正确的方向吗? I want to post data to my servlet as above and get the response back (it will be XML). 我想如上所述将数据发布到我的servlet并获取响应(它将是XML)。

The standard Java SE API offers you the java.net.URLConnection to fire and handle HTTP requests. 标准的Java SE API为您提供java.net.URLConnection来触发和处理HTTP请求。

String query = "env.adapterName=DefaultAdapter"
    + "&env.systemName=DefaultSystem"
    + "&env.userId=admin"
    + "&env.progId=PerlHttpTest";
    + "&" + URLEncoder.encode(interopApiName, "UTF-8") + "=" + URLEncoder.encode(apiName, "UTF-8")
    + "&" + URLEncoder.encode(interopApiData, "UTF-8") + "=" + URLEncoder.encode(xmlData, "UTF-8");

URLConnection connection = new URL("http://hostname/interop/InteropHttpServlet").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.getOutputStream().write(query.getBytes("UTF-8"));

InputStream response = connection.getInputStream();
// ...

There exist 3rd party API's which makes this all little easier, like Apache HttpComponents Client . 存在第三方的API,这使这一切变得简单一些,例如Apache HttpComponents Client

See also: 也可以看看:

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

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