1. 谷歌自带的json不支持像map一样直接put字符串进去,所以先导入阿里的json包
2. 创建json对象,并且放入所要请求的参数 //登录 private void loginRequest() { String url = Contents.url+"login"; JSONObject json = new JSONObject(); json.put("phone",mEtLoginUsername.getText()); json.put("password",mEtLoginPwd.getText()); // String post = "{\"phone\":\"15680659530\",\"password\":\"123456\"}"; String post = json.toString(); String user = OkHttpClientUtil.createHttpsPostByjson(url,post,"application/json"); logger.debug(user); }
3. 这里是OkHttpClientUtil工具类的方法: /** * @param url * @param json * @param contentType 参数 * @return void 返回类型 * @throws */ public static String createHttpsPostByjson(String url,String json,String contentType) { final StringBuilder buffer = new StringBuilder(""); /**忽略SSL协议证书*/ OkHttpClient build = new OkHttpClient.Builder().sslSocketFactory(createSSLSocketFactory()).hostnameVerifier(new TrustAllHostnameVerifier()).build(); MediaType mediaType = MediaType.parse("application/json;charset=UTF-8"); final RequestBody requestBody = RequestBody.create(mediaType, json);; final Request request = new Request.Builder().url(url).post(requestBody).build(); final Call call = build.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String res = response.body().string(); buffer.append(res); getSemaphoreInstance().release();//释放 } }); try { getSemaphoreInstance().acquire(); } catch (InterruptedException e1) { e1.printStackTrace(); } return buffer.toString(); }
4. 断点查看效果