An example code to invoke a HTTP GET method from Java is provided below.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLConnection; public class HTTPRequestPoster { public static String invokeGetRequest(String endpoint, String requestParameters) { String result = null; try { // Construct data StringBuffer data = new StringBuffer(); // Send data String urlstring = endpoint; urlstring += "?" + requestParameters; URL url = new URL(urlstring); //printing our URL to make sure it is correct System.out.println(urlstring); URLConnection conn = url.openConnection (); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception eft) { eft.printStackTrace(); } return result; } public static void main(String args[]) { String url="http://services.digg.com/1.0/endpoint"; //we pass three parameters to the GET request //query=search string -> PeopleSoft in our case //topic=subtopic in which we need to do the search, this is optional //count = number of results to be retrieved from digg via search String parameters="method=search.stories&query=peoplesoft&topic=programming&count=2"; String result=invokeGetRequest(url,parameters); //Just giving a SOP to print the result of the HTTP GET request System.out.println(result); } } |
Here, the parameters peoplesoft, programming and 2 are hard-coded. Making them to dynamically populate would have to be done by the code at run time. When this piece of code is executed, the code invokes a HTTP call to Digg and passes the search parameters in the GET request. The result of the HTTP call is fetched into a string buffer. All we get is the XML at the end of the execution. We will have to parse the XML to get the URLs after this.
Looking at the code, it looks very big as the approach is traditional. Moreover, till the end we have only obtained the result of the HTTP call and we have to still parse it using an XML parser (DOM4j, VTD etc).
Looking at the code, it looks very big as the approach is traditional. Moreover, till the end we have only obtained the result of the HTTP call and we have to still parse it using an XML parser (DOM4j, VTD etc).
But we are able to achieve the following :-
1) Invoke a HTTP GET request using the standard Java methods.
2) Pass the required inputs to the HTTP request.
3) Stream the response to the output.
In the next post of this series, we will understand how this can be simplified using VTD.
No comments:
Post a Comment