在安卓项目里调用API接口:该API请求数据要求是json格式,返回来的也是json格式。
get请求举例:url:xxx.api/user?userId=abc&password=123
post请求举例:url:xxx.api/user ;
apiParams: userId=abc&password=123 ;
-
callable是干什么用的?
callable用来创建子线程。和常见的Runnable和Thread实现的区别是 callable可以返回执行完的结果,其他两个不能。 -
futrue是什么用的?
futrue用来监听callable的执行情况,只要做三个事情:
1.获取执行完的结果,
2.监听是否执行完(是否取消),
3.终止线程。 -
ExecutorService线程池干什么用的?
管理线程callable,如开始一个线程。
第一个方法:submit提交一个实现Callable接口的任务,并且返回封装了异步计算结果的Future。
第二个方法:submit提交一个实现Runnable接口的任务,并且指定了在调用Future的get方法时返回的result对象。
第三个方法:submit提交一个实现Runnable接口的任务,并且返回封装了异步计算结果的Future。
package de.kayten.feposapplication.Logic;
import android.util.Log;
import org.json.JSONObject;
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.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import de.kayten.feposapplication.Common.Constant;
import de.kayten.feposapplication.Utils.ThreadPoolUtils;
public class Access {
public JSONObject POST(String con_url, String apiParams) {
JSONObject jsonObject = null;
ExecutorService threadPool = ThreadPoolUtils.getThreadPoolExecutor();
try {
HttpUtil http = new HttpUtil("POST", con_url, apiParams);
Future f = threadPool.submit(http);
jsonObject = (JSONObject) f.get();
} catch (Exception e) {
}
return jsonObject;
}
public JSONObject GET(String con_url) {
JSONObject jsonObject = null;
ExecutorService threadPool = ThreadPoolUtils.getThreadPoolExecutor();
try {
HttpUtil http = new HttpUtil("GET", con_url, "");
Future f = threadPool.submit(http);
jsonObject = (JSONObject) f.get();
} catch (Exception e) {
}
return jsonObject;
}
class HttpUtil implements Callable {
private static final String TAG = "HttpUtil";
private String apiParams;
private String Method;
private HttpURLConnection connection = null;
public HttpUtil(String Method, final String con_url, final String apiParams) {
this.Method = Method;
this.apiParams = apiParams;
InputStreamReader in = null;
try {
URL url = new URL(con_url);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setDoInput(true);
connection.setRequestMethod(Method);
connection.setRequestProperty("accept", "application/json");//请求该API要求是json格式
if (!"".equals(Constant.token)) {
String authString = "Bearer " + Constant.token;
connection.setRequestProperty("Authorization", authString);
}
if ("POST".equals(Method)) {
connection.setDoOutput(true);//post要开启输出
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(apiParams);
}
} catch (IOException e) {
e.printStackTrace();
if (connection != null)
connection.disconnect();
}
}
@Override
public JSONObject call() {
String line;
JSONObject jsonObject = null;
StringBuilder result = new StringBuilder();
try {
if(200!=connection.getResponseCode() ){
Log.e(TAG, connection.getResponseMessage());
return null;
}
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStream);
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
jsonObject = new JSONObject(result.toString());
Log.d(TAG, "run: " + result.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
return jsonObject;
}
}
}
json的解析
/*json格式的返回数据
{
"machines": [
{
"Id": 0,
"Code": "string",
"Name": "string",
"users": {
"userCode": "string",
"userName": "string"
},
"createdAt": "2019-11-04 06:21:08.521",
"updatedAt": "2019-11-04 06:21:08.521"
}
],
"offset": 0,
"limit": 0,
"total": 0
}
*/
JSONObject JO = new Access().GET(Str_url);
//获得machines的json格式数组
JSONArray JA_machines = JO .getJSONArray("machines");
//获取数组里的用户json
JSONObject JO_user = JO.getJSONObject("users");
//获取用户名
String name = JO_user.getString("userName");