开发者

Perl code to post to servlet - translate to Java?

I have the following code in Perl which posts to my开发者_JAVA百科 HTTP Servlet, calling an API with some XML data.

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. 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).


The standard Java SE API offers you the java.net.URLConnection to fire and handle HTTP requests.

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.

See also:

  • Using java.net.URLConnection to fire and handle HTTP requests
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜