This commit is contained in:
2022-03-21 11:16:38 +08:00
commit e89e807c64
1040 changed files with 284164 additions and 0 deletions

175
sdk/JAVA/README.md Normal file
View File

@@ -0,0 +1,175 @@
## 使用说明
将框架目录下的 ./SDK/JAVA/net 目录中的全部代码拷贝到项目里面即可使用。如:
![](http://7qnay5.com1.z0.glb.clouddn.com/qq20151017100539.jpg)
## 代码示例
如下是使用的代码场景片段。
首先我们需要导入SDK包
```java
//FullscreenActivity.java
import net.phalapi.sdk.*;
```
然后,准备一个子线程调用,并在此线程中实现接口请求:
```java
/**
* 网络操作相关的子线程
*/
Runnable networkTask = new Runnable() {
@Override
public void run() {
// TODO
// 在这里进行 http request.网络请求相关操作
PhalApiClient client = PhalApiClient.create()
.withHost("http://demo.phalapi.net/");
PhalApiClientResponse response = client
.withService("Default.Index")
.withParams("username", "dogstar")
.withTimeout(3000)
.request();
String content = "";
content += "ret=" + response.getRet() + "\n";
if (response.getRet() == 200) {
try {
JSONObject data = new JSONObject(response.getData());
content += "data.title=" + data.getString("title") + "\n";
content += "data.content=" + data.getString("content") + "\n";
content += "data.version=" + data.getString("version") + "\n";
} catch (JSONException ex) {
}
}
content += "msg=" + response.getMsg() + "\n";
Log.v("[PhalApiClientResponse]", content);
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", content);
msg.setData(data);
handler.sendMessage(msg);
}
};
```
接着实现线程回调的hander
```java
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value");
Log.i("mylog", "请求结果为-->" + val);
// TODO
// UI界面的更新等相关操作
}
};
```
最后在我们需要的地方启动
```java
View.OnClickListener mDummyBtnClickListener = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// 开启一个子线程进行网络操作等待有返回结果使用handler通知UI
new Thread(networkTask).start();
// ....
}
};
```
### 再一次调用和异常请求
当我们需要再次使用同一个接口实例进行请求时,需要先进行重置,以便清空之前的接口参数,如:
```java
//再一次请求
response = client.reset() //重置
.withService("User.GetBaseInfo")
.withParams("user_id", "1")
.request();
content = "";
content += "ret=" + response.getRet() + "\n";
if (response.getRet() == 200) {
try {
JSONObject data = new JSONObject(response.getData());
JSONObject info = new JSONObject(data.getString("info"));
content += "data.info.id=" + info.getString("id") + "\n";
content += "data.info.name=" + info.getString("name") + "\n";
content += "data.info.from=" + info.getString("from") + "\n";
} catch (JSONException ex) {
}
}
content += "msg=" + response.getMsg() + "\n";
Log.v("[PhalApiClientResponse]", content);
```
异常情况下即ret != 200时将返回错误的信息
```java
//再来试一下异常的请求
response = client.reset()
.withService("XXX.XXXX")
.withParams("user_id", "1")
.request();
content = "";
content += "ret=" + response.getRet() + "\n";
content += "msg=" + response.getMsg() + "\n";
Log.v("[PhalApiClientResponse]", content);
```
## 运行效果
运行后查询log可以看到
![](http://7qnay5.com1.z0.glb.clouddn.com/QQ20151017154114.jpg)
可以注意到,在调试模式时,会有接口请求的链接和返回的结果日记,如:
```
10-17 07:40:55.268: D/[PhalApiClient requestUrl](1376): http://demo.phalapi.net/?service=User.GetBaseInfo&user_id=1
10-17 07:40:55.364: D/[PhalApiClient apiResult](1376): {"ret":200,"data":{"code":0,"msg":"","info":{"id":"1","name":"dogstar","from":"oschina"}},"msg":""}
```
## 扩展你的过滤器和结果解析器
### (1)扩展过滤器
当服务端接口需要接口签名验证,或者接口参数加密传送,或者压缩传送时,可以实现此过滤器,以便和服务端操持一致。
当需要扩展时,分两步。首先,需要实现过滤器接口:
```java
class MyFilter implements PhalApiClientFilter {
public void filter(String service, Map<String, String> params) {
//TODO ...
}
}
```
然后设置过滤器:
```java
PhalApiClientResponse response = PhalApiClient.create()
.withHost("http://demo.phalapi.net/")
.withFilter(new MyFilter())
// ...
.request();
```
### (2)扩展结果解析器
当返回的接口结果不是JSON格式时可以重新实现此接口。
当需要扩展时,同样分两步。类似过滤器扩展,这里不再赘述。
## 特别注意Android之NetworkOnMainThreadException异常
由于此SDK包是使用HttpURLConnection发起请求时所以在主线程调用时会触发NetworkOnMainThreadException异常具体可参考 [Android之NetworkOnMainThreadException异常](http://blog.csdn.net/mad1989/article/details/25964495)
所以,需要使用子线程来发起请求,或者重新继承改用异步的请求。

View File

@@ -0,0 +1,218 @@
package net.phalapi.sdk;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONObject;
import android.util.Log;
/**
* PhalApi客户端SDK包JAVA版
*
* - 以接口查询语言ASQL的方式来实现接口请求
* - 出于简明客户端,将全部的类都归于同一个文件,避免过多的加载
*
* <br>使用示例:<br>
```
* PhalApiClientResponse response = PhalApiClient.create()
* .withHost("http://demo.phalapi.net/")
* .withService("Default.Index")
* .withParams("name", "dogstar")
* .withTimeout(3000)
* .request();
*
* Log.v("response ret", response.getRet() + "");
* Log.v("response data", response.getData());
* Log.v("response msg", response.getMsg());
```
*
* @package PhalApi\Response
* @license http://www.phalapi.net/license GPL 协议
* @link http://www.phalapi.net/
* @author dogstar <chanzonghuang@gmail.com> 2015-10-16
*/
public class PhalApiClient {
protected String host;
protected PhalApiClientFilter filter;
protected PhalApiClientParser parser;
protected String service;
protected int timeoutMs;
protected Map<String, String> params;
/**
* 创建一个接口实例,注意:不是单例模式
* @return PhalApiClient
*/
public static PhalApiClient create() {
return new PhalApiClient();
}
protected PhalApiClient() {
this.host = "";
this.reset();
this.parser = new PhalApiClientParserJson();
}
/**
* 设置接口域名
* @param String host
* @return PhalApiClient
*/
public PhalApiClient withHost(String host) {
this.host = host;
return this;
}
/**
* 设置过滤器与服务器的DI().filter对应
* @param PhalApiClientFilter filter 过滤器
* @return PhalApiClient
*/
public PhalApiClient withFilter(PhalApiClientFilter filter) {
this.filter = filter;
return this;
}
/**
* 设置结果解析器仅当不是JSON返回格式时才需要设置
* @param PhalApiClientParser parser 结果解析器
* @return PhalApiClient
*/
public PhalApiClient withParser(PhalApiClientParser parser) {
this.parser = parser;
return this;
}
/**
* 重置,将接口服务名称、接口参数、请求超时进行重置,便于重复请求
* @return PhalApiClient
*/
public PhalApiClient reset() {
this.service = "";
this.timeoutMs = 3000;
this.params = new HashMap<String, String>();
return this;
}
/**
* 设置将在调用的接口服务名称Default.Index
* @param String service 接口服务名称
* @return PhalApiClient
*/
public PhalApiClient withService(String service) {
this.service = service;
return this;
}
/**
* 设置接口参数,此方法是唯一一个可以多次调用并累加参数的操作
* @param String name 参数名字
* @param String value 值
* @return PhalApiClient
*/
public PhalApiClient withParams(String name, String value) {
this.params.put(name, value);
return this;
}
/**
* 设置超时时间,单位毫秒
* @param int timeoutMS 超时时间,单位毫秒
* @return PhalApiClient
*/
public PhalApiClient withTimeout(int timeoutMS) {
this.timeoutMs = timeoutMS;
return this;
}
/**
* 发起接口请求
* @return PhalApiClientResponse
*/
public PhalApiClientResponse request() {
String url = this.host;
if (this.service != null && this.service.length() > 0) {
url += "?service=" + this.service;
}
if (this.filter != null) {
this.filter.filter(this.service, this.params);
}
try {
String rs = this.doRequest(url, this.params, this.timeoutMs);
return this.parser.parse(rs);
} catch (Exception ex) {
return new PhalApiClientResponse(408, "", ex.getMessage());
}
}
protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
url = new URL(requestUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST"); // 请求方式
connection.setUseCaches(false);
connection.setConnectTimeout(timeoutMs);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//POST参数
String postContent = "";
Iterator<Entry<String, String>> iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
postContent += "&" + entry.getKey() + "=" + entry.getValue();
}
out.writeBytes(postContent);
out.flush();
out.close();
Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
Log.d("[PhalApiClient apiResult]", result);
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}

View File

@@ -0,0 +1,19 @@
package net.phalapi.sdk;
import java.util.Map;
/**
* 接口过滤器
*
* - 可用于接口签名生成
*/
public interface PhalApiClientFilter {
/**
* 过滤操作
* @param string service 接口服务名称
* @param Map<String, String> params 接口参数,注意是引用。可以直接修改
* @return null
*/
public void filter(String service, Map<String, String> params);
}

View File

@@ -0,0 +1,17 @@
package net.phalapi.sdk;
/**
* 接口结果解析器
*
* - 可用于不同接口返回格式的处理
*/
public interface PhalApiClientParser {
/**
* 结果解析
* @param String apiResult
* @return PhalApiClientResponse
*/
public PhalApiClientResponse parse(String apiResult);
}

View File

@@ -0,0 +1,24 @@
package net.phalapi.sdk;
import org.json.JSONObject;
/**
* JSON解析
*/
public class PhalApiClientParserJson implements PhalApiClientParser {
public PhalApiClientResponse parse(String apiResult) {
if (apiResult == null) {
return new PhalApiClientResponse(408, "", "Request Timeout");
}
try {
JSONObject jsonObj = new JSONObject(apiResult);
return new PhalApiClientResponse(
jsonObj.getInt("ret"), jsonObj.getString("data"), jsonObj.getString("msg"));
} catch (Exception ex) {
return new PhalApiClientResponse(500, "", "Internal Server Error Or " + ex.getMessage());
}
}
}

View File

@@ -0,0 +1,45 @@
package net.phalapi.sdk;
/**
* 接口返回结果
*
* - 与接口返回的格式对应即有ret/data/msg
*/
public class PhalApiClientResponse {
protected int ret;
protected String data;
protected String msg;
/**
* 完全构造函数
* @param int ret
* @param String data
* @param String msg
*/
public PhalApiClientResponse(int ret, String data, String msg) {
this.ret = ret;
this.data = data;
this.msg = msg;
}
public PhalApiClientResponse(int ret, String data) {
this(ret, data, "");
}
public PhalApiClientResponse(int ret) {
this(ret, "", "");
}
public int getRet() {
return this.ret;
}
public String getData() {
return this.data;
}
public String getMsg() {
return this.msg;
}
}