Android——Post的请求格式Json格式和表单格式

发送Post请求一般有两种格式:Json格式和表单格式来发送请求。

这里两个工具类来使用发送post请求:

表单格式:

//表单body
FormBody body = new FormBody.Builder().add("news_id", news_id + "").add("fromname", fromname).add("time", time).build();

public static void getPost(FormBody body, String httpurl) {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Builder();

        builder.post(body);
        builder.url(httpurl);
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(Call arg0, Response arg1) throws IOException {
                // TODO Auto-generated method stub
                Log.i("lpl", arg1.body().string());
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub

            }
        });
    }



Json格式发送:

public static String MypostJson(String api, Object RequestJsonbean) throws IOException {
        /**
         * 返回的仍然是json格式
         */
        Gson gson = new Gson();
        String json = gson.toJson(RequestJsonbean);
        OkHttpClient client = new OkHttpClient();

        //json body
        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);
        }
    }

RequestJsonbean是你的javabean对象

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值