解决问题
正确:
{
"data":
{accesstoken : "odA5niNeOhhi1cIK0eOGhrxCB7ClG9R4gl%2Fa2%2FNcOaJ42tWayXKZZZBgIPsh1tRLshlxWyXlEyY...",
expirein :"2017-11-27 14:49:23"
},
"flag":1,
"success":1,
"expired":0
}
错误:
{
flag:1,
expired :0,
success : 0,
err :{
code :"xxx",
Msg :"密码错误"
}
}
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lenovo.pcsd.bp.businesspartner.bean.UserModel;
import okhttp3.*;
import java.util.HashMap;
import java.util.Map;
public class HttpUtils {
public static Map post(String url,Object obj){
//创建连接客户端
OkHttpClient client = new OkHttpClient();
//使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
Gson gson = new Gson();
//使用Gson将对象转换为json字符串
String json = gson.toJson(obj);
//MediaType 设置Content-Type 标头中包含的媒体类型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request request = new Request.Builder()
.url(url)//请求的url
.post(requestBody)
.build();
Call call = client.newCall(request);
Response response;//执行
{
try {
response = call.execute();
if (response.isSuccessful()) {
String result=response.body().string();
Map<String,String> resultMap=new HashMap<String, String>();
if(JSONObject.parseObject(result).get("success").equals(1)){
JSONObject object = JSONObject.parseObject(result).getJSONObject("data");
String accesstoken= (String) object.get("accesstoken");
String expirein= (String) object.get("expirein");
resultMap.put("success","1");
resultMap.put("accesstoken",accesstoken);
resultMap.put("expirein",expirein);
}else {
String errCode = (String) JSONObject.parseObject(result).getJSONObject("err").get("code");
String errMsg = (String) JSONObject.parseObject(result).getJSONObject("err").get("msg");
resultMap.put("success","0");
resultMap.put("errCode",errCode);
resultMap.put("errMsg",errMsg);
}
return resultMap;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}