Android开发中运用okhttp发送网络请求

发布时间:2019-06-18 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Android开发中运用okhttp发送网络请求脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

下载

okhttp的gIThup地址,可以看到是支持maven和gradle导入的:
https://github.com/square/okhttp
首页文档:
http://square.github.io/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();

脚本宝典总结

以上是脚本宝典为你收集整理的Android开发中运用okhttp发送网络请求全部内容,希望文章能够帮你解决Android开发中运用okhttp发送网络请求所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。