使用OKHTTP方式发送POST请求,获取返回的JSON串

//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"));
}

 

posted @ 2021-12-13 17:13  信铁寒胜  阅读(4282)  评论(0编辑  收藏  举报