2016-12-27 69 views
0

我一直在尋找最簡單的方法將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專家。我想如果有人會解釋我需要做什麼,最好有例子。提前致謝

+1

要調用執行'()',它會執行當前線程上的請求。該線程似乎是主要的應用程序線程,所以你會崩潰。使用'enqueue()'而不是'execute()'讓OkHttp在後臺線程上執行HTTP請求。 – CommonsWare

+0

有人可以幫忙,寫下爲什麼沒有這個工作? http://stackoverflow.com/a/41351476/7313961 – JuliusCezarus

回答

0

由於@CommonsWare和@christian已經說過,你需要網絡操作是在後臺和這個目標Okhttp有一個特殊的方法enqueue()。這將爲您創建後臺線程並簡化您的工作。

在你的情況,裏面run()方法行更改這些:

String run(String url) throws IOException { 

    String result = ""; 

    Request request = new Request.Builder() 
     .url(url) 
     .build(); 

    Response response = client.newCall(request).enqueue(new Callback() { 

     @Override 
     public void onFailure(Call call, IOException e) { 
      // failure case 
     } 

     @Override 
     public void onResponse(Call call, Response response) throws IOException { 
      // success case 
      result = response.body().string(); 
     } 
    }); 
} 
相關問題