JAVA_PHP_Koala HW模擬程式 [JAVA 和 PHP 實現 restful api 通訊]

JAVA_PHP_Koala HW模擬程式 [JAVA 和 PHP 實現 restful api 通訊]

JAVA_PHP_Koala HW模擬程式 [JAVA 和 PHP 實現 restful api 通訊]


參考資料:http://techsupport.megvii.com/hc/kb/article/178244/

GITHUB: https://github.com/jash-git/JAVA_PHP_Koala-restful-api



目標:按照參考資料撰寫對應的『JAVA Client』 和對應的 『模擬用PHP SERVER』


PHP[authLogin API 模擬]~koala_authLogin.php
    01.抓取/紀錄(寫入檔案)所以Client的所有Header資訊
    02.抓取/紀錄(寫入檔案)Client傳送過來的JSON資料

    03.撰寫輸出對應JSON資訊,達到Client可以判斷並認為登入成功

<?php
	function GetAllHeader()
	{
		// 忽略获取的header数据。这个函数后面会用到。主要是起过滤作用
		$ignore = array('host','accept','content-length','content-type'); 
		$headers = array();
		//这里大家有兴趣的话,可以打印一下。会出来很多的header头信息。咱们想要的部分,都是‘http_'开头的。所以下面会进行过滤输出。
		/*var_dump($_SERVER);
		exit;*/
 
		foreach($_SERVER as $key=>$value){
			if(substr($key, 0, 5)==='HTTP_'){
				//这里取到的都是'http_'开头的数据。
				//前去开头的前5位
				$key = substr($key, 5);
				//把$key中的'_'下划线都替换为空字符串
				$key = str_replace('_', ' ', $key);
				//再把$key中的空字符串替换成‘-’
				$key = str_replace(' ', '-', $key);
				//把$key中的所有字符转换为小写
				$key = strtolower($key);
 
				//这里主要是过滤上面写的$ignore数组中的数据
				if(!in_array($key, $ignore)){
					$headers[$key] = $value;
				}
			}
		}
		//输出获取到的header
		return $headers;
	}
	//header('Content-Type: application/json; charset=UTF-8'); //設定資料類型為 json,編碼 utf-8
	set_time_limit(0);//確保不會超時
	date_default_timezone_set("Asia/Taipei");
	$filename="client_header_".date('Y-m-d-H-i-s').".txt";
	$myfile = fopen($filename, "w") or die("Unable to open file!");
	foreach (getallheaders() as $name => $value) {
		fwrite($myfile, "$name: $value\n");
	}	  
	fwrite($myfile, "\n=========================\n\n");
	foreach (GetAllHeader() as $name => $value) {
		fwrite($myfile, "$name: $value\n");	
	}
	fwrite($myfile, "\n=========================\n\n");
	foreach($_SERVER as $key=>$value){
		fwrite($myfile, "$key: $value\n");		
	}
	fwrite($myfile, "\n=========================\n\n");
	
	$data = file_get_contents("php://input");//接收client set json data
	fwrite($myfile, "client set json data: $data\n");	
	
	fwrite($myfile, "\n=========================\n\n");
	
	$Subarraydata=array();
	$Subarraydata["id"]=200;
	
	$arraydata=array();
	$arraydata["code"]=0;
	$arraydata["data"]=$Subarraydata;
	
	echo json_encode($arraydata);	
	fclose($myfile);
?>

JAVA[呼叫 authLogin API]
    01.按照參考資料建立 authLogin 函數

package test01;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class test01 {

    public static CookieStore authLogin(String url,String username,String password) throws Exception {
        /**
    	    * http://techsupport.megvii.com/hc/kb/article/178244/
    	    * 登录 获取 Cookie
    	    * @param url API地址
    	    * @param username 账号, 注意不要使用admin@megvii.com
    	    * @param password 密码
    	    * @return cookie CookieStore
    	    * @throws Exception 
    	*/    	
        System.out.println("Start /auth/login to ...");
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost request = new HttpPost(url);
         
        //设置user-agent为 "Koala Admin" 
        //设置Content-Type为 "application/json"
        request.setHeader("User-Agent", "Koala Admin");
        request.setHeader("Content-Type", "application/json");
         
        JSONObject json = new JSONObject();
        json.put("username", username);
        json.put("password", password);
         
        request.setEntity(new StringEntity(json.toString(), "UTF-8"));
         
        //发起网络请求,获取结果值
        HttpClientContext context = HttpClientContext.create();
        System.out.println("Send data:"+json.toString());
        CloseableHttpResponse response = httpclient.execute(request, context);  
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //---
        //A JSONObject text must begin with '{' at 1 [character 2 line 1]
        //https://blog.csdn.net/u012860950/article/details/77884515
        int i = responseBody.indexOf("{");
        responseBody = responseBody.substring(i);
        //---A JSONObject text must begin with '{' at 1 [character 2 line 1]
        System.out.println("Get data:"+responseBody);

       
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("Login failed, code:" + result);
        }else{
            System.out.println("Login Success,id:" + resp.getJSONObject("data").getInt("id"));
            return  context.getCookieStore();
        }
        return null;
    }
    
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.print("Hello World!\n");
		try {
			authLogin("http://127.0.0.1/Koala_authLogin.php","jashliao","123456789");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

4 thoughts on “JAVA_PHP_Koala HW模擬程式 [JAVA 和 PHP 實現 restful api 通訊]

  1. 註記[實測與機器連線: URL和接收到的JSON]

    authLogin(“http://192.168.1.237/auth/login”,”test@admin.com”,”123456″);

    Hello World!
    Start /auth/login to …
    Send data:{“password”:”123456″,”username”:”test@admin.com”}
    Get data:{
    “code”: 0,
    “data”: {
    “avatar”: “”,
    “company”: {
    “attendance_on”: true,
    “attendance_weekdays”: [
    1,
    2,
    3,
    4,
    5
    ],
    “consigner”: “\u66f2”,
    “create_time”: 1558543636,
    “data_version”: 1,
    “deployment”: 1,
    “door_range”: [
    [
    0,
    0
    ],
    [
    24,
    0
    ]
    ],
    “door_weekdays”: [
    1,
    2,
    3,
    4,
    5,
    6,
    7
    ],
    “feature_version”: 7,
    “fmp_on”: false,
    “full_day”: true,
    “id”: 1,
    “logo”: “/static/images/logo.png”,
    “name”: “\u5ba2\u6237”,
    “notdetermined_on”: true,
    “remark”: “”,
    “scenario”: “\u6b63\u5e38\u4f7f\u7528”,
    “upload”: true,
    “yellowlist_warn”: true
    },
    “company_id”: 1,
    “id”: 2,
    “organization_id”: null,
    “password_reseted”: true,
    “permission”: [],
    “role_id”: 2,
    “username”: “test@admin.com”,
    “verify”: false
    },
    “page”: {}
    }

  2. 收到的實際JSON 轉 C# Class

    public class Company
    {
    public bool attendance_on { get; set; }
    public List attendance_weekdays { get; set; }
    public string consigner { get; set; }
    public int create_time { get; set; }
    public int data_version { get; set; }
    public int deployment { get; set; }
    public List<List> door_range { get; set; }
    public List door_weekdays { get; set; }
    public int feature_version { get; set; }
    public bool fmp_on { get; set; }
    public bool full_day { get; set; }
    public int id { get; set; }
    public string logo { get; set; }
    public string name { get; set; }
    public bool notdetermined_on { get; set; }
    public string remark { get; set; }
    public string scenario { get; set; }
    public bool upload { get; set; }
    public bool yellowlist_warn { get; set; }
    }

    public class Data
    {
    public string avatar { get; set; }
    public Company company { get; set; }
    public int company_id { get; set; }
    public int id { get; set; }
    public object organization_id { get; set; }
    public bool password_reseted { get; set; }
    public List permission { get; set; }
    public int role_id { get; set; }
    public string username { get; set; }
    public bool verify { get; set; }
    }

    public class Page
    {
    }

    public class RootObject
    {
    public int code { get; set; }
    public Data data { get; set; }
    public Page page { get; set; }
    }

  3. 使用C# 用 JAVA 為參照 實際測試真實API 可以得到下面結果

    C# 原始碼 以更新到 GITHUB上

    {“code”:0,”data”:{“avatar”:””,”company”:{“attendance_on”:true,”attendance_weekdays”:[1,2,3,4,5],”consigner”:”\u66f2″,”create_time”:1558543636,”data_version”:1,”deployment”:1,”door_range”:[[0,0],[24,0]],”door_weekdays”:[1,2,3,4,5,6,7],”feature_version”:7,”fmp_on”:false,”full_day”:true,”id”:1,”logo”:”/static/images/logo.png”,”name”:”\u5ba2\u6237″,”notdetermined_on”:true,”remark”:””,”scenario”:”\u6b63\u5e38\u4f7f\u7528″,”upload”:true,”yellowlist_warn”:true},”company_id”:1,”id”:2,”organization_id”:null,”password_reseted”:true,”permission”:[],”role_id”:2,”username”:”test@admin.com”,”verify”:false},”page”:{}}

jash.liao@qq.com 發表迴響 取消回覆

你的電子郵件位址並不會被公開。 必要欄位標記為 *