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可以判斷並認為登入成功
$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 账号, 注意不要使用[email protected] * @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(); } } }