当前位置:   article > 正文

android okhttp打印请求头_Android开发中运用okhttp发送网络请求

android okhttpclient无法打印出header

最近因为一些原因重新接触弃疗好久的android,突然发现在之前的版本中android比较用的比较多的httpclient不能用了…现在的异步访问方式用起来又感觉有点麻烦,然后经一个同学提醒想起来一个大牛学长之前在项目中用过的okhttp,然后就用了下,其实速度和使用方式还是很不错的,但是遇到了一些小问题,在这里笔记下。

下载

如果使用maven和gradle配置只要按照github页面的方法将其加入到相关的配置文件里就行了,如果下载的是jar包,可以通过androidstudio的

File > Project Structrue > dependencies

然后add file dependence来添加

这里需要的包有两个

okio.jar

okhttp.jar

URL paramter参数的的Get、Post请求

官网上已有说明如下,但是我遇到的问题其实主要是发送x-www-form-urlencoded参数的post请求,所以这里就笔记一下官网的文档好了…

GET

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()

.url(url)

.build();

Response response = client.newCall(request).execute();

return response.body().string();

POST

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();

return response.body().string();

}

x-www-form-urlencoded参数的Post请求

OkHttpClient okHttpClient = new OkHttpClient();

RequestBody body = new FormEncodingBuilder()

.add("user", user)

.add("password", pwd)

.build();

Request request = new Request.Builder()

.url("youurl")

.post(body)

.build();

Response response = okHttpClient.newCall(request).execute();

String result = response.body().string();

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号