您的位置:首页 > 理论基础 > 计算机网络

Okhttp POST请求

2016-09-13 19:15 155 查看

随着安卓的快速发展,网络请求的框架也随之改变,而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");
是固定写法;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: