试试这个
添加Gradle取决于
compile 'com.squareup.okhttp3:okhttp:3.2.0'
public static JSonObject foo(String url, JSonObject json) { JSonObject jsonObjectResp = null; try { MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); okhttp3.RequestBody body = RequestBody.create(JSON, json.toString()); okhttp3.Request request = new okhttp3.Request.Builder() .url(url) .post(body) .build(); okhttp3.Response response = client.newCall(request).execute(); String networkResp = response.body().string(); if (!networkResp.isEmpty()) { jsonObjectResp = parseJSonStringToJSONObject(networkResp); } } catch (Exception ex) { String err = String.format("{"result":"false","error":"%s"}", ex.getMessage()); jsonObjectResp = parseJSonStringToJSONObject(err); } return jsonObjectResp; }解析响应
private static JSonObject parseJSonStringToJSONObject(final String strr) { JSonObject response = null; try { response = new JSonObject(strr); } catch (Exception ex) { // Log.e("Could not parse malformed JSON: "" + json + """); try { response = new JSonObject(); response.put("result", "failed"); response.put("data", strr); response.put("error", ex.getMessage()); } catch (Exception exx) { } } return response;}


