OkHttp之post请求发送给服务器json

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static String MypostJson(String api, Object RequestJsonbean) throws IOException {
        /**
         * 返回的仍然是json格式
         */
        Gson gson = new Gson();
        String json = gson.toJson(RequestJsonbean);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(api).post(body).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

你可能感兴趣的:(OkHttp之post请求发送给服务器json)