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
精彩评论