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; }