OkHttp简单使用
程序员文章站
2022-03-12 19:55:14
OkHttp是一个轻量优秀的网络框架。用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,) 使用方法: 1、在 build.gradle中添加okHttp依赖 2、创建一个全局的OkHttpClient 3 ......
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; }