OkHttp3 快速实现post一个JSON数据

public class HttpToPost{

    private int id;

    Gson gson = new Gson();

    //自己的回调接口
    private ReturnHttpResult returnHttpResult;
   
    OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public HttpToSettingClassified(int id) {
        this.id= id;
    }

    public void saveSettingMsg() {

        Map map = new HashMap<>();
        map.put("id", id);
        String param= gson.toJson(map);

        RequestBody requestBody = RequestBody.create(JSON, param);
        Request request = new Request.Builder()
                .post(requestBody)
                .url("自己的接口地址")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                returnHttpResult.clickReturnHttpResult(e.getMessage());
                Log.d(TAG, "onFailure: 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                returnHttpResult.clickReturnHttpResult(result);
                Log.d(TAG, "onResponse: " + result);
            }
        });

    }

    //回调得到response内容
    public void setReturnHttpResult(ReturnHttpResult returnHttpResult) {
        this.returnHttpResult = returnHttpResult;
    }
}

 

你可能感兴趣的:(AndroidStudio)