android 开发笔计(1) 获取远程数据

由于要支持https,所以选了okhttp 这个库

  • 在app\build.gradle中添加 compile 'com.squareup.okhttp3:okhttp:3.5.0'
  • 添加文件,并导入
import okhttp3.OkHttpClient;  
import okhttp3.Request;  
import okhttp3.Response;  
  • 编写代码
     public static String get(String url) {
        try {
            Log.d(TAG, "url:" + url);
            client.newBuilder().connectTimeout(10000, TimeUnit.MILLISECONDS);
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }