//okHttp方式訪問方式
package com.haier.interconn.monitor.utils;
import okhttp3.*;
import okhttp3.Response;
import java.io.IOException;
/**
* Created by 01457141 on 2017/8/8.
*/
public class HttpUtils {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient client = new OkHttpClient();
public static Response post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response;
}
public static Response get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response;
}
}
//通過ServiceIml調用okHttp方式發送post請求,得到返回的json數據
public Map<String,String> checkUsernameAndPassword(String username, String password, String host) {
Response response = null;
StringBuilder url = new StringBuilder();
//臨時數據類型
JSONObject jsonObjectTemp = new JSONObject();
JSONObject[] jsonArrayTemp = new JSONObject[1];
JSONArray jsonResultArrayTemp = null;
String StringTemp;
JSONObject jsonObjectRequest = new JSONObject();
Map<String,String> resultMap = new HashMap<>();
try {
//構建指定json格式,使用post方式訪問接口,格式模板
/* {
"loginInfos":[
{
"userName":"haieradmin",
"passwd":"Haier,1231",
"host":"10.135.106.249"
}
]
} */
url.setLength(0);
url.append(ToolConfig.MACHINE_MONITOR_URL).append("init");
jsonObjectTemp.put("userName",username);
jsonObjectTemp.put("passwd", password);
jsonObjectTemp.put("host", host);
jsonArrayTemp[0] = jsonObjectTemp;
jsonObjectRequest.put("loginInfos",jsonArrayTemp);
response = HttpUtils.post(url.toString(), jsonObjectRequest.toString());
//解析返回的json數據
StringTemp = response.body().string();
jsonObjectTemp = (JSONObject) JSONObject.parse(StringTemp);
jsonResultArrayTemp = (JSONArray) jsonObjectTemp.get("results");
resultMap.put("status",jsonResultArrayTemp.getJSONObject(0).getString("status"));
resultMap.put("message",jsonResultArrayTemp.getJSONObject(0).getString("message"));
} catch (IOException e) {
e.printStackTrace();
}
return resultMap;
}
}
//拿到返回的map進行數據的判斷
Map<String,String> result = machineIpService.checkUsernameAndPassword(username,password,ip);
if(result.get("status").equals("FAILED")){
return Response.fail(Constant.CODE_NEGATIVE_ONE,result.get("message"));
}