HttpRequest.java 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package com.example.yiupang.freefoodfinder;
  2. import android.os.AsyncTask;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.fasterxml.jackson.databind.type.TypeFactory;
  5. import java.io.BufferedReader;
  6. import java.io.BufferedWriter;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStream;
  10. import java.io.OutputStreamWriter;
  11. import java.io.UnsupportedEncodingException;
  12. import java.net.HttpURLConnection;
  13. import java.net.URL;
  14. import java.net.URLEncoder;
  15. import java.util.HashMap;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.Map;
  19. /**
  20. * Created by yiupang on 5/27/2017.
  21. *
  22. */
  23. class HttpRequest extends AsyncTask<HttpCall, String, String>
  24. {
  25. private static final String UTF_8 = "UTF-8";
  26. /**
  27. * Handle the input and result of the HTTP call
  28. *
  29. * @param params - The parameters of the asynchronous task from the caller are passed to this step
  30. * */
  31. @Override
  32. protected String doInBackground(HttpCall... params)
  33. {
  34. HttpURLConnection urlConnection = null;
  35. StringBuilder response = new StringBuilder();
  36. try
  37. {
  38. HttpCall httpCall = params[0];
  39. URL url;
  40. OutputStream os;
  41. BufferedWriter writer;
  42. int responseCode;
  43. url = new URL(httpCall.getUrl());
  44. urlConnection = (HttpURLConnection) url.openConnection();
  45. urlConnection.setRequestMethod(HttpCall.methodToStr(httpCall.getMethodType()));
  46. urlConnection.setReadTimeout(10000 /* milliseconds */);
  47. urlConnection.setConnectTimeout(15000 /* milliseconds */);
  48. if(httpCall.getBody() != null && httpCall.getMethodType() != HttpCall.GET)
  49. {
  50. urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  51. os = urlConnection.getOutputStream();
  52. writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
  53. writer.append(httpCall.getBody().toString());
  54. writer.flush();
  55. writer.close();
  56. os.close();
  57. }
  58. /*Handle the response*/
  59. responseCode = urlConnection.getResponseCode();
  60. if(responseCode == HttpURLConnection.HTTP_OK)
  61. {
  62. String line;
  63. BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
  64. while ((line = br.readLine()) != null)
  65. {
  66. response.append(line);
  67. }
  68. }
  69. }
  70. catch (Exception e)
  71. {
  72. e.printStackTrace();
  73. }
  74. finally
  75. {
  76. if(urlConnection != null) {
  77. urlConnection.disconnect();
  78. }
  79. }
  80. return response.toString();
  81. }
  82. /**
  83. * Invoke on the UI thread after the background computation finishes.
  84. *
  85. * @param s - the returned value from doInBackground()
  86. * */
  87. @Override
  88. protected void onPostExecute(String s)
  89. {
  90. super.onPostExecute(s);
  91. try
  92. {
  93. ObjectMapper mapper = new ObjectMapper();
  94. TypeFactory typeFactory = mapper.getTypeFactory();
  95. List<Event> events = mapper.readValue(s, typeFactory.constructCollectionType(List.class, Event.class));/*Parse to Event Objs*/
  96. onResponse(events);
  97. }
  98. catch (IOException e)
  99. {
  100. List<Event> eventsError = new LinkedList<>();
  101. eventsError.add(new Event("Error", "Error", "Error"));
  102. onResponse(eventsError);
  103. }
  104. }
  105. /**
  106. * It needs to be overwritten by the caller to handle the response
  107. * */
  108. public void onResponse(List<Event> response)
  109. {
  110. }
  111. /**
  112. * Create the string for parameters in the URL based on the attributes and data passed by the caller
  113. * */
  114. private String getDataString(HashMap<String, String> params, int methodType) throws UnsupportedEncodingException
  115. {
  116. StringBuilder result = new StringBuilder();
  117. boolean isFirst = true;
  118. for(Map.Entry<String, String> entry : params.entrySet())
  119. {
  120. if(isFirst)
  121. {
  122. isFirst = false;
  123. if(methodType == HttpCall.GET)
  124. result.append("?");
  125. else
  126. result.append("&");
  127. result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
  128. result.append("=");
  129. result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
  130. }
  131. }
  132. return result.toString();
  133. }
  134. }