RequestUtil.java 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package com.yyrh.networking.urlhttp;
  2. import android.text.TextUtils;
  3. import com.yyrh.behavior.ReportLogUtil;
  4. import org.json.JSONException;
  5. import org.json.JSONObject;
  6. import java.io.BufferedReader;
  7. import java.io.File;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.HttpURLConnection;
  12. import java.net.URLEncoder;
  13. import java.util.List;
  14. import java.util.Map;
  15. import static com.yyrh.constant.URLConstants.ACTION_LOG_URL;
  16. /**
  17. * Created by fighting on 2017/4/24.
  18. */
  19. class RequestUtil{
  20. private Thread mThread;
  21. /**
  22. * 一般的get请求或post请求
  23. */
  24. RequestUtil(String method,String url, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {
  25. switch (method){
  26. case "GET":
  27. urlHttpGet(url,paramsMap,headerMap,callBack);
  28. break;
  29. case "POST":
  30. urlHttpPost(url,paramsMap,null,headerMap,callBack);
  31. break;
  32. }
  33. }
  34. /**
  35. * post请求,传递json格式数据。
  36. */
  37. RequestUtil(String url, String jsonStr, Map<String, String> headerMap, CallBackUtil callBack) {
  38. urlHttpPost(url,null,jsonStr,headerMap,callBack);
  39. }
  40. /**
  41. * 上传文件
  42. */
  43. RequestUtil(String url, File file ,List<File> fileList,Map<String,File> fileMap,String fileKey,String fileType, Map<String,String> paramsMap, Map<String, String> headerMap,CallBackUtil callBack) {
  44. urlHttpUploadFile(url,file,fileList,fileMap,fileKey,fileType,paramsMap,headerMap,callBack);
  45. }
  46. /**
  47. * get请求
  48. */
  49. private void urlHttpGet(final String url, final Map<String, String> paramsMap, final Map<String, String> headerMap, final CallBackUtil callBack) {
  50. mThread = new Thread(new Runnable() {
  51. @Override
  52. public void run() {
  53. RealResponse response = new RealRequest().getData(getUrl(url,paramsMap),headerMap);
  54. if(response.code == HttpURLConnection.HTTP_OK){
  55. callBack.onSeccess(response);
  56. }else {
  57. callBack.onError(response);
  58. }
  59. }
  60. });
  61. }
  62. /**
  63. * post请求
  64. */
  65. private void urlHttpPost(final String url, final Map<String, String> paramsMap, final String jsonStr, final Map<String, String> headerMap, final CallBackUtil callBack) {
  66. mThread = new Thread(new Runnable() {
  67. @Override
  68. public void run() {
  69. RealResponse response = new RealRequest().postData(url, getPostBody(paramsMap,jsonStr),getPostBodyType(paramsMap,jsonStr),headerMap);
  70. if(response.code == HttpURLConnection.HTTP_OK){
  71. callBack.onSeccess(response);
  72. }else {
  73. callBack.onError(response);
  74. if (!url.startsWith(ACTION_LOG_URL)){
  75. resportErrorLog(url,response);
  76. }
  77. }
  78. }
  79. });
  80. }
  81. /**
  82. * 上报接口错误日志
  83. */
  84. private void resportErrorLog(String url,RealResponse response){
  85. String errorMessage = "";
  86. if(response.inputStream != null){
  87. errorMessage = getRetString(response.inputStream);
  88. }else if(response.errorStream != null) {
  89. errorMessage = getRetString(response.errorStream);
  90. }else if(response.exception != null) {
  91. errorMessage = response.exception.getMessage();
  92. }else {
  93. errorMessage = "";
  94. }
  95. String tag =url.split("/")[url.split("/").length-1];
  96. JSONObject json = new JSONObject();
  97. try {
  98. json.put("errorMessage",errorMessage);
  99. } catch (JSONException e) {
  100. e.printStackTrace();
  101. }
  102. ReportLogUtil.reportErrorLog(tag,tag,json.toString());
  103. }
  104. /**
  105. * 上传文件
  106. */
  107. private void urlHttpUploadFile(final String url, final File file , final List<File> fileList, final Map<String,File> fileMap, final String fileKey, final String fileType, final Map<String,String> paramsMap, final Map<String, String> headerMap, final CallBackUtil callBack) {
  108. mThread = new Thread(new Runnable() {
  109. @Override
  110. public void run() {
  111. RealResponse response = null;
  112. response = new RealRequest().uploadFile(url, file,fileList,fileMap,fileKey,fileType,paramsMap,headerMap,callBack);
  113. if(response.code == HttpURLConnection.HTTP_OK){
  114. callBack.onSeccess(response);
  115. }else {
  116. callBack.onError(response);
  117. }
  118. }
  119. });
  120. }
  121. /**
  122. * get请求,将键值对凭接到url上
  123. */
  124. private String getUrl(String path,Map<String, String> paramsMap) {
  125. if(paramsMap != null){
  126. path = path+"?";
  127. for (String key: paramsMap.keySet()){
  128. path = path + key+"="+paramsMap.get(key)+"&";
  129. }
  130. path = path.substring(0,path.length()-1);
  131. }
  132. return path;
  133. }
  134. /**
  135. * 得到post请求的body
  136. */
  137. private String getPostBody(Map<String, String> params,String jsonStr) {//throws UnsupportedEncodingException {
  138. if(params != null){
  139. return getPostBodyFormParameMap(params);
  140. }else if(!TextUtils.isEmpty(jsonStr)){
  141. return jsonStr;
  142. }
  143. return null;
  144. }
  145. /**
  146. * 根据键值对参数得到body
  147. */
  148. private String getPostBodyFormParameMap(Map<String, String> params) {//throws UnsupportedEncodingException {
  149. StringBuilder result = new StringBuilder();
  150. boolean first = true;
  151. try {
  152. for (Map.Entry<String, String> entry : params.entrySet()) {
  153. if (first)
  154. first = false;
  155. else
  156. result.append("&");
  157. result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
  158. result.append("=");
  159. result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
  160. }
  161. return result.toString();
  162. } catch (UnsupportedEncodingException e) {
  163. return null;
  164. }
  165. }
  166. /**
  167. * 得到bodyType
  168. */
  169. private String getPostBodyType(Map<String, String> paramsMap, String jsonStr) {
  170. if(paramsMap != null){
  171. //return "text/plain";不知为什么这儿总是报错。目前暂不设置(20170424)
  172. return null;
  173. }else if(!TextUtils.isEmpty(jsonStr)){
  174. return "application/json;charset=utf-8";
  175. }
  176. return null;
  177. }
  178. /**
  179. * 开启子线程,调用run方法
  180. */
  181. void execute(){
  182. if(mThread != null){
  183. mThread.start();
  184. }
  185. }
  186. private static String getRetString(InputStream is) {
  187. String buf;
  188. try {
  189. BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
  190. StringBuilder sb = new StringBuilder();
  191. String line = "";
  192. while ((line = reader.readLine()) != null) {
  193. sb.append(line + "\n");
  194. }
  195. is.close();
  196. buf = sb.toString();
  197. return buf;
  198. } catch (Exception e) {
  199. return null;
  200. }
  201. }
  202. }