1. 在build.gradle里引入okhttp库
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.google.code.gson:gson:2.6.2' }
2. 创建okhttp对象,这里是用赖汉模式,减少系统的记忆体消耗。
public class OkHttp { // okHttp private static OkHttpClient okHttpClient; // 饿汉式 private static OkHttp okHttp = new OkHttp(); private OkHttp(){} public static OkHttp getInstance(){ okHttpClient = new OkHttpClient(); return okHttp; } }
3. 在okhttp对象里创建getResponse方法,返回服务器的回应。
// 取得數據 private Request request; private Response response; private String strContext; public String getResponse(String strURL) { try { // 创建okhttp Builder,从URL返回服务器的回应 request = new Request.Builder() .url(strURL) .build(); // response储存服务器的回应 response = okHttpClient.newCall(request).execute(); // 把response转换成string strContext = response.body().string(); }catch (IOException e) { strContext = e.toString(); } return strContext; }
4. 如果是想利用okhttp上传文件,可用uploadImage方法。
// 上傳圖片 private String uploadResult; public String uploadImage(String URL, String userId, File file, String fileName) { try { // MultipartBuilder,是上传文件的query // addFormDataPart方法:@param [String]name, [String]value // addFormDataPart方法:@param [String]name, [String]fileName, [String]fileType, [String]file RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addFormDataPart("portrait", fileName, RequestBody.create(MediaType.parse("image/jpg"), file)) .addFormDataPart("userId", userId) .addFormDataPart("action", "updateProtrait") .build(); // request方法: @param [String]URL, [RequestBody]requestBody Request request = new Request.Builder() .url(URL) .post(requestBody) .build(); // response储存服务器的回应 Response response = okHttpClient.newCall(request).execute(); // 把response转换成string uploadResult = response.body().string(); } catch (IOException e) { uploadResult = e.toString(); } return uploadResult; }