You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

218 lines
5.9 KiB

  1. package net.phalapi.sdk;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLEncoder;
  9. import java.util.HashMap;
  10. import java.util.Iterator;
  11. import java.util.Map;
  12. import java.util.Map.Entry;
  13. import org.json.JSONObject;
  14. import android.util.Log;
  15. /**
  16. * PhalApi客户端SDK包(JAVA版)
  17. *
  18. * - 以接口查询语言(ASQL)的方式来实现接口请求
  19. * - 出于简明客户端,将全部的类都归于同一个文件,避免过多的加载
  20. *
  21. * <br>使用示例:<br>
  22. ```
  23. * PhalApiClientResponse response = PhalApiClient.create()
  24. * .withHost("http://demo.phalapi.net/")
  25. * .withService("Default.Index")
  26. * .withParams("name", "dogstar")
  27. * .withTimeout(3000)
  28. * .request();
  29. *
  30. * Log.v("response ret", response.getRet() + "");
  31. * Log.v("response data", response.getData());
  32. * Log.v("response msg", response.getMsg());
  33. ```
  34. *
  35. * @package PhalApi\Response
  36. * @license http://www.phalapi.net/license GPL 协议
  37. * @link http://www.phalapi.net/
  38. * @author dogstar <chanzonghuang@gmail.com> 2015-10-16
  39. */
  40. public class PhalApiClient {
  41. protected String host;
  42. protected PhalApiClientFilter filter;
  43. protected PhalApiClientParser parser;
  44. protected String service;
  45. protected int timeoutMs;
  46. protected Map<String, String> params;
  47. /**
  48. * 创建一个接口实例,注意:不是单例模式
  49. * @return PhalApiClient
  50. */
  51. public static PhalApiClient create() {
  52. return new PhalApiClient();
  53. }
  54. protected PhalApiClient() {
  55. this.host = "";
  56. this.reset();
  57. this.parser = new PhalApiClientParserJson();
  58. }
  59. /**
  60. * 设置接口域名
  61. * @param String host
  62. * @return PhalApiClient
  63. */
  64. public PhalApiClient withHost(String host) {
  65. this.host = host;
  66. return this;
  67. }
  68. /**
  69. * 设置过滤器,与服务器的DI().filter对应
  70. * @param PhalApiClientFilter filter 过滤器
  71. * @return PhalApiClient
  72. */
  73. public PhalApiClient withFilter(PhalApiClientFilter filter) {
  74. this.filter = filter;
  75. return this;
  76. }
  77. /**
  78. * 设置结果解析器,仅当不是JSON返回格式时才需要设置
  79. * @param PhalApiClientParser parser 结果解析器
  80. * @return PhalApiClient
  81. */
  82. public PhalApiClient withParser(PhalApiClientParser parser) {
  83. this.parser = parser;
  84. return this;
  85. }
  86. /**
  87. * 重置,将接口服务名称、接口参数、请求超时进行重置,便于重复请求
  88. * @return PhalApiClient
  89. */
  90. public PhalApiClient reset() {
  91. this.service = "";
  92. this.timeoutMs = 3000;
  93. this.params = new HashMap<String, String>();
  94. return this;
  95. }
  96. /**
  97. * 设置将在调用的接口服务名称,如:Default.Index
  98. * @param String service 接口服务名称
  99. * @return PhalApiClient
  100. */
  101. public PhalApiClient withService(String service) {
  102. this.service = service;
  103. return this;
  104. }
  105. /**
  106. * 设置接口参数,此方法是唯一一个可以多次调用并累加参数的操作
  107. * @param String name 参数名字
  108. * @param String value 值
  109. * @return PhalApiClient
  110. */
  111. public PhalApiClient withParams(String name, String value) {
  112. this.params.put(name, value);
  113. return this;
  114. }
  115. /**
  116. * 设置超时时间,单位毫秒
  117. * @param int timeoutMS 超时时间,单位毫秒
  118. * @return PhalApiClient
  119. */
  120. public PhalApiClient withTimeout(int timeoutMS) {
  121. this.timeoutMs = timeoutMS;
  122. return this;
  123. }
  124. /**
  125. * 发起接口请求
  126. * @return PhalApiClientResponse
  127. */
  128. public PhalApiClientResponse request() {
  129. String url = this.host;
  130. if (this.service != null && this.service.length() > 0) {
  131. url += "?service=" + this.service;
  132. }
  133. if (this.filter != null) {
  134. this.filter.filter(this.service, this.params);
  135. }
  136. try {
  137. String rs = this.doRequest(url, this.params, this.timeoutMs);
  138. return this.parser.parse(rs);
  139. } catch (Exception ex) {
  140. return new PhalApiClientResponse(408, "", ex.getMessage());
  141. }
  142. }
  143. protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
  144. String result = null;
  145. URL url = null;
  146. HttpURLConnection connection = null;
  147. InputStreamReader in = null;
  148. url = new URL(requestUrl);
  149. connection = (HttpURLConnection) url.openConnection();
  150. connection.setDoInput(true);
  151. connection.setDoOutput(true);
  152. connection.setRequestMethod("POST"); // 请求方式
  153. connection.setUseCaches(false);
  154. connection.setConnectTimeout(timeoutMs);
  155. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  156. //POST参数
  157. String postContent = "";
  158. Iterator<Entry<String, String>> iter = params.entrySet().iterator();
  159. while (iter.hasNext()) {
  160. Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
  161. postContent += "&" + entry.getKey() + "=" + entry.getValue();
  162. }
  163. out.writeBytes(postContent);
  164. out.flush();
  165. out.close();
  166. Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);
  167. in = new InputStreamReader(connection.getInputStream());
  168. BufferedReader bufferedReader = new BufferedReader(in);
  169. StringBuffer strBuffer = new StringBuffer();
  170. String line = null;
  171. while ((line = bufferedReader.readLine()) != null) {
  172. strBuffer.append(line);
  173. }
  174. result = strBuffer.toString();
  175. Log.d("[PhalApiClient apiResult]", result);
  176. if (connection != null) {
  177. connection.disconnect();
  178. }
  179. if (in != null) {
  180. try {
  181. in.close();
  182. } catch (IOException e) {
  183. e.printStackTrace();
  184. }
  185. }
  186. return result;
  187. }
  188. }