android okhttputils post json对象,使用OKHTTP方式发送POST请求,获取返回的JSON串

本文展示了如何使用OkHttp库在Android中发送POST请求,将JSON对象作为请求体,并解析返回的JSON响应。通过HttpUtils类的post方法发送请求,构造指定格式的JSON数据,并在checkUsernameAndPassword方法中处理响应,获取并处理返回的Map数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

okHttp方式访问方式

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 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 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 result = machineIpService.checkUsernameAndPassword(username,password,ip);

if(result.get("status").equals("FAILED")){

return Response.fail(Constant.CODE_NEGATIVE_ONE,result.get("message"));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值