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

OkHttp使用教程

2016-12-08 10:34 225 查看
转载自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html

部分:

HTTP GET

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();    if (response.isSuccessful()) {        return response.body().string();
} else {        throw new IOException("Unexpected code " + response);
}
}


HTTP POST

POST提交Json数据

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
f (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}


使用Request的post方法来提交请求体RequestBody
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: