2016-10-04 78 views
1

嘗試在普通Java類中進行頁面切換時一切正常,但如果已經在Android應用中完成此操作,則會出現問題:「您沒有權限訪問」,而用戶代理在Android清單規定必須使用互聯網而這一切都在一個單獨的線程的權限,可有人面對這個問題無法使用Jsoup獲取頁面

public void onClick(View view) 
{ 
    new Thread(new Runnable() { 
     @Override 
     public void run() 
     { 
      go(); 
     } 
    }).start(); 
} 
private void go() 
{ 

    try { 
     document = Jsoup.connect("http://issa.beltelecom.by/main.html").userAgent("Chrome 53.0.2785.143").ignoreHttpErrors(true).get(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

你嘗試在後臺任務運行呢? –

+0

當然是的 – Grauen

回答

0

這似乎是設置Accept頭字段重要(注:在Android 5.1.1設備測試)。

一般情況下:如果使用jsoup拒絕連接,請檢查請求(例如使用chrome dev tools/F12中的網絡選項卡)並添加缺少的標題字段。

示例代碼

String userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"; 
String url = "https://issa.beltelecom.by/main.html"; 
String acceptValue = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; 
String host = "issa.beltelecom.by"; 

document = Jsoup.connect(url).header("Accept",acceptValue).header("Host", host).userAgent(userAgent).get(); 
+0

感謝兄弟我添加接受和它的工作 – Grauen

+0

@Grauen歡迎您,謝謝您的反饋意見。 –

0

你可以試試這個,設置你的OnClickListener調用後臺任務。

new MyAsyncTask().execute(); 

然後執行你的任務

private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> { 

      protected void onPreExecute() { 
       super.onPreExecute(); 
       //do anything here 
      } 

      protected Boolean doInBackground(Void...param) { 

       Document document = null; 
       try { 
        document = Jsoup.connect(getString(R.string.your_url_string)).get(); 

       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

       if (document != null) { 
        Elements yourElements = document.select("#element_id"); 

        //Do anything here 
        return true; 
       } 
       //Document is null 
       return false; 
      } 

      protected void onPostExecute(Boolean result) { 
       if(result==true) { 
        // do this 
       } 
      } 
     } 
+0

這不起作用,這裏的主要問題是服務器阻止訪問頁面,雖然如果我在普通的java類中運行相同的代碼一切正在工作 – Grauen

+0

如果您在普通的Java中運行代碼類和它運行,那麼我想這不是你的服務器,它阻止它。但是你做錯了什麼。 –

+0

但其他網站都工作正常 – Grauen