Calling WebServices through HttpClient


/ Published in: Java
Save to your folder(s)

A RestClient class for calling webservice using both, get and post methods, and getting the response dropped into an String.


Copy this code and paste it in your HTML
  1. public class RestClient {
  2.  
  3. private ArrayList<NameValuePair> params;
  4. private ArrayList<NameValuePair> headers;
  5.  
  6. private String url;
  7.  
  8. private int responseCode;
  9. private String message;
  10.  
  11. private String response;
  12.  
  13. public String getResponse() {
  14. return response;
  15. }
  16.  
  17. public String getErrorMessage() {
  18. return message;
  19. }
  20.  
  21. public int getResponseCode() {
  22. return responseCode;
  23. }
  24.  
  25. public RestClient(String url)
  26. {
  27. this.url = url;
  28. params = new ArrayList<NameValuePair>();
  29. headers = new ArrayList<NameValuePair>();
  30. }
  31.  
  32. public void AddParam(String name, String value)
  33. {
  34. params.add(new BasicNameValuePair(name, value));
  35. }
  36.  
  37. public void AddHeader(String name, String value)
  38. {
  39. headers.add(new BasicNameValuePair(name, value));
  40. }
  41.  
  42. public void Execute(RequestMethod method) throws Exception
  43. {
  44. switch(method) {
  45. case GET:
  46. {
  47. //add parameters
  48. String combinedParams = "";
  49. if(!params.isEmpty()){
  50. combinedParams += "?";
  51. for(NameValuePair p : params)
  52. {
  53. String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),�UTF-8�);
  54. if(combinedParams.length() > 1)
  55. {
  56. combinedParams += "&" + paramString;
  57. }
  58. else
  59. {
  60. combinedParams += paramString;
  61. }
  62. }
  63. }
  64.  
  65. HttpGet request = new HttpGet(url + combinedParams);
  66.  
  67. //add headers
  68. for(NameValuePair h : headers)
  69. {
  70. request.addHeader(h.getName(), h.getValue());
  71. }
  72.  
  73. executeRequest(request, url);
  74. break;
  75. }
  76. case POST:
  77. {
  78. HttpPost request = new HttpPost(url);
  79.  
  80. //add headers
  81. for(NameValuePair h : headers)
  82. {
  83. request.addHeader(h.getName(), h.getValue());
  84. }
  85.  
  86. if(!params.isEmpty()){
  87. request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
  88. }
  89.  
  90. executeRequest(request, url);
  91. break;
  92. }
  93. }
  94. }
  95.  
  96. private void executeRequest(HttpUriRequest request, String url)
  97. {
  98. HttpClient client = new DefaultHttpClient();
  99.  
  100. HttpResponse httpResponse;
  101.  
  102. try {
  103. httpResponse = client.execute(request);
  104. responseCode = httpResponse.getStatusLine().getStatusCode();
  105. message = httpResponse.getStatusLine().getReasonPhrase();
  106.  
  107. HttpEntity entity = httpResponse.getEntity();
  108.  
  109. if (entity != null) {
  110.  
  111. InputStream instream = entity.getContent();
  112. response = convertStreamToString(instream);
  113.  
  114. // Closing the input stream will trigger connection release
  115. instream.close();
  116. }
  117.  
  118. } catch (ClientProtocolException e) {
  119. client.getConnectionManager().shutdown();
  120. e.printStackTrace();
  121. } catch (IOException e) {
  122. client.getConnectionManager().shutdown();
  123. e.printStackTrace();
  124. }
  125. }
  126.  
  127. private static String convertStreamToString(InputStream is) {
  128.  
  129. StringBuilder sb = new StringBuilder();
  130.  
  131. String line = null;
  132. try {
  133. while ((line = reader.readLine()) != null) {
  134. sb.append(line + "\n");
  135. }
  136. } catch (IOException e) {
  137. e.printStackTrace();
  138. } finally {
  139. try {
  140. is.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. return sb.toString();
  146. }
  147. }
  148.  
  149.  
  150. /*
  151. Here is an example of how I use the class to call the Google Analytics API. I use the AddParam methods to add query string / post values and the AddHeader method to add headers to the request. RequestMethod is a simple enum with GET and POST values.
  152. */
  153.  
  154. RestClient client = new RestClient(LOGIN_URL);
  155. client.AddParam("accountType", "GOOGLE");
  156. client.AddParam("source", "tboda-widgalytics-0.1");
  157. client.AddParam("Email", _username);
  158. client.AddParam("Passwd", _password);
  159. client.AddParam("service", "analytics");
  160. client.AddHeader("GData-Version", "2");
  161.  
  162. try {
  163. client.Execute(RequestMethod.POST);
  164. } catch (Exception e) {
  165. e.printStackTrace();
  166. }
  167.  
  168. String response = client.getResponse();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.