2015-09-26 43 views
0

我正在爲一個計算項目編寫一個Android應用程序。我有一段代碼將下載網頁的html並將其存儲爲字符串 - 但它不會下載整個html的主體。Android-下載html時間表的主體

下面是我使用的代碼:

package com.example.pete.computingproject; 

import android.app.Activity; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.widget.Toast; 

import java.net.URL; 
import java.net.URLConnection; 
import java.util.Scanner; 

import android.preference.PreferenceManager; 
import android.content.SharedPreferences; 


public class async extends AsyncTask<String, String, String> { 
private Context mContext; 

public async(Context context) { 
    mContext = context; 
} 
@Override 

protected String doInBackground(String... strings) { 

    String content = null; 
    URLConnection connection = null; 


    // TODO Auto-generated method stub 

    try { 
     connection = new URL("https://stars.cirencester.ac.uk/index_bypass.php?view=tab_content/timetable&wk=6&stu_id=142669").openConnection(); 
     Scanner scanner = new Scanner(connection.getInputStream()); 
     scanner.useDelimiter("\\Z"); 
     content = scanner.next(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    System.out.println(content); 
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); 
    SharedPreferences.Editor editor = preferences.edit(); 
    editor.putString("timetable1", content); 
    editor.apply(); 
    return (content); 




} 


} 

我想下載以下頁面的源代碼(點擊右鍵,查看源代碼) https://stars.cirencester.ac.uk/index_bypass.php?view=tab_content/timetable&wk=6&wk_num=&year=2015&stu_id=142669

不過代碼我使用由於某種原因在第40行停止工作。我需要所有這些爲我的應用程序工作。任何幫助,將不勝感激! 如果可能,我只想對當前的代碼進行微小的調整。但是,如果沒有使用完全不同的代碼沒有辦法做到這一點,請讓我知道。 謝謝!

+1

但是長代碼是,請包括在你的問題。 –

回答

0

我推薦使用依賴關係「OkHttp」,而不是在套接字上打破頭,爲你完成的工作。

添加dependecy: 編譯 'com.squareup.okhttp:okhttp:2.5.0'

詳細瞭解如何使用它 瞭解更多來自這裏:https://github.com/square/okhttp/wiki/Recipes

+0

我正在使用android studio,而且我對Android也很陌生(如果你沒有注意到的話)。這是在香草android兼容還是這是一個外部庫?我對使用它們持謹慎態度,因爲我以前沒有這樣做。 – Dave

+0

它是java庫,意味着它可以運行在任何平臺上,可以運行java(basiclly),我相信它也可以在香草上運行,我自己也沒試過。 無論如何,它的「導入」到項目中,就像「附加代碼」一樣,只需要「導入」庫,並且可以使用它提供的方法。 你可以在這裏瞭解更多:http://square.github.io/okhttp/ –