Okhttp现在已经成为Android开发者的标配,现在我们进行Okhttp基本功能实现,包括get请求,post请求。
首先在AndroidStudio项目中打开build.gradle(Module:app),然后导入Okhttp库
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.squareup.okhttp3:okhttp:3.4.1' }
先来来看看简单的get请求,
private OkHttpClient okHttpClient; okHttpClient=new OkHttpClient(); Request request = new Request.Builder() .url("https://www.baidu.com") .build();
这样向百度首页发送请求就成功了。
如果还想查看返回的源码,加上如下就好了
Response response =okHttpClient.newCall((request).execute);
String responseData=response.body().string();
再来看看稍微复杂一点点的post请求。
RequestBody requestBody=new FormBody.Builder() .add("参数名","参数内容") .add("参数名2","参数内容2") .build(); Request request=new Request.Builder() .url("https://www.baidu.com") .post(requestBody) .build();就是这么简单,获取网页源代码的方式和上面的get一样。