天天看點

Okhttp系列:簡單的不用傳參的Get請求示例

網絡權限

<uses-permission android:name="android.permission.INTERNET"/>
           

引入okhttp包:

implementation 'com.squareup.okhttp3:okhttp:3.14.4'
           

在app module下的build.gradle檔案中配置java8,否則會報錯。

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        ...
    }

    buildTypes {
      ...
    }

	// 增加java8的配置 
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
           

MainActivity代碼

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://publicobject.com/helloworld.txt";
                //初始化okhttp用戶端
                OkHttpClient client  = new OkHttpClient();

                //建立請求體
                Request request = new Request.Builder().url(url).get().build();
                //執行請求
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    //擷取伺服器響應資料
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        Log.e("xxx", result);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
           

最終效果

Okhttp系列:簡單的不用傳參的Get請求示例