Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
阿新 • • 發佈:2021-08-24
加入OkHttp的依賴
implementation 'com.google.code.gson:gson:2.8.6'
建立一個OkHttpClient的例項
OkHttpClient client = new OkHttpClient();
傳送HTTP請求,build方法之前有很多的連綴可以豐富這個Request物件,比如通過url方法來設定目標的網路地址
Request request = new Request.Builder()
.url(address)
.build();
之後呼叫OkHttpClient的newCall方法來建立一個Call物件,並呼叫它的execute方法來發送請求並獲取伺服器返回的資料
//高版本Android預設禁止Http請求,要放開http請求
Response response = client.newCall(request).execute();
Response物件就是伺服器返回的資料,我們可以使用如下寫法來得到返回的具體內容
//要用.body().string()方法,而不是直接.string()
String responseData = response.body().string();
傳送POST請求
//構造一個requestBody,填充相關資料 RequestBody requestBody = new FormBody.Builder() .add("username", "root") .add("password", "admin") .build(); //傳送Post請求 Request request = new Request.Builder() .url("https://www.baidu.com") .post(requestBody) .build(); //處理Post請求的回覆 try { Response requestAboutPost = client.newCall(request).execute(); String response = requestAboutPost.body().string(); } catch (IOException e) { e.printStackTrace(); }