Guest User

Untitled

a guest
Jul 31st, 2018
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.99 KB | None | 0 0
  1. public class RestClient {
  2.  
  3. private boolean authentication;
  4. private ArrayList<NameValuePair> headers;
  5.  
  6. private String jsonBody;
  7. private String message;
  8.  
  9. private ArrayList<NameValuePair> params;
  10. private String response;
  11. private int responseCode;
  12.  
  13. private String url;
  14.  
  15. // HTTP Basic Authentication
  16. private String username;
  17. private String password;
  18.  
  19. protected Context context;
  20.  
  21. public RestClient(String url) {
  22. this.url = url;
  23. params = new ArrayList<NameValuePair>();
  24. headers = new ArrayList<NameValuePair>();
  25. }
  26. //Be warned that this is sent in clear text, don't use basic auth unless you have to.
  27. public void addBasicAuthentication(String user, String pass) {
  28. authentication = true;
  29. username = user;
  30. password = pass;
  31. }
  32.  
  33. public void addHeader(String name, String value) {
  34. headers.add(new BasicNameValuePair(name, value));
  35. }
  36.  
  37. public void addParam(String name, String value) {
  38. params.add(new BasicNameValuePair(name, value));
  39. }
  40.  
  41. public void execute(RequestMethod method) throws Exception {
  42. switch (method) {
  43. case GET: {
  44. HttpGet request = new HttpGet(url + addGetParams());
  45. request = (HttpGet) addHeaderParams(request);
  46. executeRequest(request, url);
  47. break;
  48. }
  49. case POST: {
  50. HttpPost request = new HttpPost(url);
  51. request = (HttpPost) addHeaderParams(request);
  52. request = (HttpPost) addBodyParams(request);
  53. executeRequest(request, url);
  54. break;
  55. }
  56. case PUT: {
  57. HttpPut request = new HttpPut(url);
  58. request = (HttpPut) addHeaderParams(request);
  59. request = (HttpPut) addBodyParams(request);
  60. executeRequest(request, url);
  61. break;
  62. }
  63. case DELETE: {
  64. HttpDelete request = new HttpDelete(url);
  65. request = (HttpDelete) addHeaderParams(request);
  66. executeRequest(request, url);
  67. }
  68. }
  69. }
  70.  
  71. private HttpUriRequest addHeaderParams(HttpUriRequest request)
  72. throws Exception {
  73. for (NameValuePair h : headers) {
  74. request.addHeader(h.getName(), h.getValue());
  75. }
  76.  
  77. if (authentication) {
  78.  
  79. UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
  80. username, password);
  81. request.addHeader(new BasicScheme().authenticate(creds, request));
  82. }
  83.  
  84. return request;
  85. }
  86.  
  87. private HttpUriRequest addBodyParams(HttpUriRequest request)
  88. throws Exception {
  89. if (jsonBody != null) {
  90. request.addHeader("Content-Type", "application/json");
  91. if (request instanceof HttpPost)
  92. ((HttpPost) request).setEntity(new StringEntity(jsonBody,
  93. "UTF-8"));
  94. else if (request instanceof HttpPut)
  95. ((HttpPut) request).setEntity(new StringEntity(jsonBody,
  96. "UTF-8"));
  97.  
  98. } else if (!params.isEmpty()) {
  99. if (request instanceof HttpPost)
  100. ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params,
  101. HTTP.UTF_8));
  102. else if (request instanceof HttpPut)
  103. ((HttpPut) request).setEntity(new UrlEncodedFormEntity(params,
  104. HTTP.UTF_8));
  105. }
  106. return request;
  107. }
  108.  
  109. private String addGetParams() throws Exception {
  110. //Using StringBuffer append for better performance.
  111. StringBuffer combinedParams = new StringBuffer();
  112. if (!params.isEmpty()) {
  113. combinedParams.append("?");
  114. for (NameValuePair p : params) {
  115. combinedParams.append((combinedParams.length() > 1 ? "&" : "")
  116. + p.getName() + "="
  117. + URLEncoder.encode(p.getValue(), "UTF-8"));
  118. }
  119. }
  120. return combinedParams.toString();
  121. }
  122.  
  123. public String getErrorMessage() {
  124. return message;
  125. }
  126.  
  127. public String getResponse() {
  128. return response;
  129. }
  130.  
  131. public int getResponseCode() {
  132. return responseCode;
  133. }
  134.  
  135. public void setContext(Context ctx) {
  136. context = ctx;
  137. }
  138.  
  139. public void setJSONString(String data) {
  140. jsonBody = data;
  141. }
  142.  
  143. private void executeRequest(HttpUriRequest request, String url) {
  144.  
  145. DefaultHttpClient client = new DefaultHttpClient();
  146. HttpParams params = client.getParams();
  147.  
  148. // Setting 30 second timeouts
  149. HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
  150. HttpConnectionParams.setSoTimeout(params, 30 * 1000);
  151.  
  152. HttpResponse httpResponse;
  153.  
  154. try {
  155. httpResponse = client.execute(request);
  156. responseCode = httpResponse.getStatusLine().getStatusCode();
  157. message = httpResponse.getStatusLine().getReasonPhrase();
  158.  
  159. HttpEntity entity = httpResponse.getEntity();
  160.  
  161. if (entity != null) {
  162.  
  163. InputStream instream = entity.getContent();
  164. response = convertStreamToString(instream);
  165.  
  166. // Closing the input stream will trigger connection release
  167. instream.close();
  168. }
  169.  
  170. } catch (ClientProtocolException e) {
  171. client.getConnectionManager().shutdown();
  172. e.printStackTrace();
  173. } catch (IOException e) {
  174. client.getConnectionManager().shutdown();
  175. e.printStackTrace();
  176. }
  177. }
  178.  
  179. private static String convertStreamToString(InputStream is) {
  180.  
  181. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  182. StringBuilder sb = new StringBuilder();
  183.  
  184. String line = null;
  185. try {
  186. while ((line = reader.readLine()) != null) {
  187. sb.append(line + "\n");
  188. }
  189. } catch (IOException e) {
  190. e.printStackTrace();
  191. } finally {
  192. try {
  193. is.close();
  194. } catch (IOException e) {
  195. e.printStackTrace();
  196. }
  197. }
  198. return sb.toString();
  199. }
Add Comment
Please, Sign In to add comment