提交數據結構:
{
"taskid" : "f204c46f869e68c6979f50a5281250c4196a9f3a",
"data": [
{
"taskid": "fb32fc1e08fa75204cbabfc80fa4c43ad72fd630", // 任務id 唯一
"TimeStamp": 1582107884000, //數據時間,毫秒時間戳
"VideoRate": "42.091"
},
{
"taskid": "fb32fc1e08fa75204cbabfc80fa4c43ad72fd630", // 任務id 唯一
"TimeStamp": 1582107884000, //數據時間,毫秒時間戳
"VideoRate": "42.091"
}]
}
implementation 'com.squareup.okhttp3:okhttp:3.14.2'
postman請求:
MainActivity中:
@Override
public void onClick(View view) {
if (view.equals(button3)){//實時數據回傳
//開啓一個線程,做聯網操作
new Thread() {
@Override
public void run() {
postJson();
}
}.start();
}
private void postJson() {
//申明給服務端傳遞一個json串
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
try {
jsonObject.put("taskid","7e44afffa884a7476acf77aa6bc083bb1b2aeaff");
jsonObject.put("data",jsonArray);
JSONObject jsonObject1=new JSONObject();
jsonArray.put(0,jsonObject1);
jsonObject1.put("taskid","");
jsonObject1.put("TimeStamp", Calendar.getInstance().getTimeInMillis());
jsonObject1.put("VideoRate",43);
} catch (JSONException e) {
e.printStackTrace();
}
String json=jsonObject.toString();
Log.i(TAG,json);
//創建一個OkHttpClient對象
OkHttpClient okHttpClient = new OkHttpClient();
//創建一個RequestBody(參數1:數據類型 參數2傳遞的json串)
RequestBody requestBody = RequestBody.create(JSON, json);
//創建一個請求對象
Request request = new Request.Builder()
.url("http://10.10.20.39/platform/public/index.php/api/data/live")
.post(requestBody)
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: " + response.body().string());
}
});
}