Okhttp POST请求

随着安卓的快速发展,网络请求的框架也随之改变,而okhttp的框架的使用越来越多,下面就是okhttp的post请求 的用法,还是比较简单的。如以下代码;

<span style="font-size:18px;background-color: rgb(255, 255, 255);"> public static final MediaType JSON =MediaType.parse("application/json; charset=utf-8");


 public static String getjsonData(String path ,String json){</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//创建okhttpclient的对象
        OkHttpClient client = new OkHttpClient();</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);"></span><pre class="hljs java" style="padding: 9.5px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; color: rgb(101, 123, 131); border-radius: 4px; margin-top: 0px; margin-bottom: 20px; line-height: 20px; word-break: break-all; word-wrap: normal; border: 1px solid rgba(0, 0, 0, 0.14902); overflow: auto; background: rgb(253, 246, 227);"><code class="java" style="padding: 0px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12px; border-radius: 3px; border: none; background-color: transparent;"><span class="hljs-comment" style="color: rgb(147, 161, 161);">//创建一个RequestBody(参数1:数据类型 参数2传递的json串)</span></code>
RequestBody body = RequestBody.create(JSON, json);
//创建一个请求对象
Request request = new Request.Builder().url(path).post(body).build();
 
 
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//通过client获取Call的对象
        Call call = client.newCall(request);
        try {</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//获取相应
            Response response = call.execute();</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//获取响应码
            int code = response.code();
            if (code==200){</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//通过响应对象获取响应的body
                ResponseBody body1 = response.body();</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//通过body获取字节数组
                byte[] bytes = body1.bytes();</span>
<span style="font-size:18px;background-color: rgb(255, 255, 255);">//吧数组转化为我们从网络上请求的数据;
                ss = bytes.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  ss;</span>
注意;
public static final MediaType JSON =MediaType.parse("application/json; charset=utf-8");
是固定写法;


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值