我一直在尋找最簡單的方法將Html代碼轉換爲字符串一段時間。我只需要取回它,以便我可以繼續我的項目。如何使用OkHttp將html源代碼轉換爲字符串 - Android
我想:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
String html= null;
try {
html = run("http://google.com");
} catch (IOException e) {
e.printStackTrace();
}
text.setText(html);
}
}
我得到了錯誤android.os.NetworkOnMainThreadException。
我剛開始在Android工作室開發,我也不是Java專家。我想如果有人會解釋我需要做什麼,最好有例子。提前致謝
要調用執行'()',它會執行當前線程上的請求。該線程似乎是主要的應用程序線程,所以你會崩潰。使用'enqueue()'而不是'execute()'讓OkHttp在後臺線程上執行HTTP請求。 – CommonsWare
有人可以幫忙,寫下爲什麼沒有這個工作? http://stackoverflow.com/a/41351476/7313961 – JuliusCezarus