OkHttp简单使用
OkHttp是一个轻量优秀的网络框架。用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,)
使用方法:
1、在 build.gradle中添加okHttp依赖
//okHttp implementation \'com.squareup.okhttp3:okhttp:3.11.0\'
2、创建一个全局的OkHttpClient
//全局使用一个OkHttpClient private static final OkHttpClient client=new OkHttpClient();
3、Get请求
public static String Get(String url) { String result = null; Request request = new Request.Builder() .url(url) .build(); try { Response response = client.newCall(request).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return result; }
4、POST请求(通过键值对传递参数)
public static String Post(String url, List<NameValuePair> paramList) { String result = null; FormBody.Builder builder = new FormBody.Builder(); for (NameValuePair param : paramList) { builder.add(param.getName(), param.getValue()); } FormBody formBody = builder.build(); Request request = new Request.Builder().url(url).post(formBody).build(); try { Response response = client.newCall(request).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return result; }
版权声明:本文为tangchun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。