HttpRequest.java 4.0 KB

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